How to Create an Array Filled with a Specific Value in JavaScript
A common task in programming is to initialize an array of a certain size where every element has the same starting value. This is useful for creating placeholder data, initializing a game board, or setting up a data structure before populating it. The modern and most direct way to achieve this is with the Array.fill() method.
This guide will teach you how to use Array.fill() to create an array with a specific value. Crucially, it will also explain the critical difference between filling an array with primitive values (like strings or numbers) versus non-primitive values (like objects or arrays), and show you the correct approach for each.
The Core Method: Array(N).fill(value)
The Array.prototype.fill() method is the standard, built-in tool for this job. It changes all elements in an array to a static value.
The logic:
- Create an array of a specific length using the
Array(N)constructor. This creates a sparse array withNempty slots. - Call
.fill()on this new array, passing the value you want to use.
For example, you need to create an array of length 3, where every element is the string 'a'. How to generate that array?
This clean, one-line solution is the best practice for primitive values.
const length = 3;
const value = 'a';
const newArray = Array(length).fill(value);
console.log(newArray); // Output: ['a', 'a', 'a']
The Critical Distinction: Primitives vs. Objects
The fill() method has a very important behavior that you must understand:
- When used with primitive values (strings, numbers, booleans), it works as expected, filling the array with copies of the value.
- When used with non-primitive values (objects, arrays), it fills the array with references to the exact same object.
This distinction is the source of a very common bug.
Creating an Array of Objects (The Correct Way)
If you need to create an array containing N distinct objects (that all happen to look the same), you cannot use Array.fill({}). The correct tool for this is Array.from().
The Array.from() method can take a "mapping function" as a second argument. This function is called for each element being created, and its return value is used to populate the array. This ensures that a new, unique object is created for every element.
Solution:
const length = 3;
// The second argument is a function that runs for each of the 3 elements.
// Each time it runs, it returns a new object.
const newArray = Array.from({ length: length }, () => {
return { name: 'Tom Nolan' };
});
console.log(newArray);
Output:
[
{ name: 'Tom Nolan' },
{ name: 'Tom Nolan' },
{ name: 'Tom Nolan' }
]
Now, each object in the array is a separate instance.
Why Array(N).fill({}) is a Bug (Problem with .fill() and Objects)
Let's demonstrate why filling an array with an object is a trap.
const length = 3;
const initialObject = { name: 'Alice' };
const newArray = Array(length).fill(initialObject);
// Now, let's try to change the name of only the first user.
newArray[0].name = 'Tom';
// The change is reflected in ALL the elements!
console.log(newArray);
Output: (This is the bug!)
[
{ name: 'Tom' },
{ name: 'Tom' },
{ name: 'Tom' }
]
This happens because fill() copied the reference to initialObject into all three slots of the array. All three elements are pointing to the exact same object in memory.
Best Practice: Never use Array.fill() to initialize an array with a non-primitive value unless you specifically intend for all elements to be a reference to the same object. For creating an array of distinct objects, always use Array.from() with a mapping function.
Conclusion
Initializing an array with a repeated value is a simple task in JavaScript, as long as you use the right tool for the type of data you are working with.
- To create an array of primitive values (strings, numbers, etc.), the best and most concise method is
Array(N).fill(value). - To create an array of distinct objects or arrays, the correct and professional method is
Array.from({ length: N }, () => ({...})).
By understanding the crucial difference in how fill() handles primitives versus objects, you can avoid a common and frustrating bug in your code.