Borislav Hadzhiev
Sun Nov 07 2021·2 min read
Photo by Anthony Tran
Use the fill()
method to initialize an array of objects, e.g.
new Array(2).fill({key: 'value'})
. The Array()
constructor creates an array
of a specified length and the fill()
method sets the elements in an array to
the provided value and returns the result.
const arr1 = new Array(2).fill({key: 'value'}); // 👇️ [{key: 'value'}, {key: 'value'}] console.log(arr1);
The parameter we passed to the Array() constructor is the number of empty elements the array should contain.
console.log(new Array(2)); // 👉️ [ , ]
What the Array()
constructor does under the hood is, it sets the array's
length to the provided value.
const arr = []; arr.length = 2; console.log(arr); // 👉️ [ , ]
We need an array of N empty elements, so we can replace the value of each with an object using the fill() method.
The only parameter we passed to the fill
method is the value we want to fill
the array with.
Each of the 2
elements in the array gets assigned a value of an object.
fill()
method is not supported in Internet Explorer. If you have to support the browser, use a for loop instead.To initialize an array of objects, use the Array()
constructor to create an
array filled with N empty elements and use a for loop to iterate over the array
assigning each element to an object.
const arr2 = new Array(2); for (let i = 0; i < arr2.length; i++) { arr2[i] = {key: 'value'}; } // 👇️ [{key: 'value'}, {key: 'value'}] console.log(arr2);
We used the Array()
constructor to create an array of 2
empty elements.
The for loop allows us to iterate over the array and assign each empty element to an object.
fill()
method if supported, because it's declarative, easy to read and solves the exact problem of filling an array with a specific value.