How to Initialize an Array of Objects in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

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 element 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.

Alternatively, you can use a simple for loop.

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, because it's declarative, easy to read and solves the exact problem of filling an array with a specific value.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.