How to Initialize an Array of Objects in JavaScript

avatar

Borislav Hadzhiev

Sun Nov 07 20212 min read

banner

Photo by Anthony Tran

Initialize an Array of Objects in JavaScript #

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.

index.js
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.

index.js
console.log(new Array(2)); // ๐Ÿ‘‰๏ธ [ , ]

What the Array() constructor does under the hood is, it sets the array's length to the provided value.

index.js
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.

The fill() method is not supported in Internet Explorer. If you have to support the browser, use a for loop instead.

Initialize an Array of Objects using for loop #

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.

index.js
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.

Which approach you pick is a matter of personal preference. I'd go with the fill() method if supported, because it's declarative, easy to read and solves the exact problem of filling an array with a specific value.

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee