Skip to main content

How to Initialize an Array with Objects in JavaScript

A common task in programming is to create an array pre-populated with a specific number of objects, often with a default structure or a sequential ID. This is useful for creating placeholder data, initializing a game board, or setting up a default state.

This guide will teach you the modern, standard methods for initializing an array with objects. You will learn the recommended best practice using Array.from() and understand the critical pitfall of using Array.prototype.fill() with objects.

The Array.from() static method is the most concise, readable, and powerful tool for this job. It can create a new array of a specific length and provides a mapping function to generate the content for each element.

The logic: we use a two-argument version of Array.from():

  1. First Argument: An "array-like" object with a length property (e.g., { length: 3 }).
  2. Second Argument: A mapping function that is called for each new element. On each iteration, we return a new object.

For example, we need to create an array containing three identical objects.

// Problem: How to create an array with 3 objects like { key: 'value' }?
const desiredLength = 3;

Solution:

const length = 3;

const newArray = Array.from({ length: length }, () => ({
key: 'value'
}));

console.log(newArray);

Output:

[ { key: 'value' }, { key: 'value' }, { key: 'value' } ]
note

This is the recommended best practice because it creates a new, distinct object for each element in the array. ::

You can also use the index provided by the mapping function to create objects with unique properties:

const newArrayWithIds = Array.from({ length: 3 }, (_, index) => ({
id: index + 1,
status: 'pending',
}));

console.log(newArrayWithIds);

Output:

[ { id: 1, status: 'pending' }, { id: 2, status: 'pending' }, { id: 3, status: 'pending' } ]

The Common Pitfall to Avoid: Array.prototype.fill()

A common mistake is to use the fill() method to populate an array with objects. While this seems to work, it has a major flaw: it fills the array with references to the same object.

Example of code with errors:

// ⛔️ This is an anti-pattern and will cause bugs!
const newArray = new Array(3).fill({ key: 'value' });

On the surface, this looks correct. But if you try to modify one of the objects, you'll see the problem.

const newArray = new Array(3).fill({ key: 'value' });

// Modify the first object
newArray[0].key = 'NEW VALUE';

// The change is reflected in ALL objects because they are the same reference!
console.log(newArray);

Output:

[
{ key: 'NEW VALUE' },
{ key: 'NEW VALUE' },
{ key: 'NEW VALUE' }
]
note

This happens because fill() copies the reference to the object, not the object itself. To avoid this, you must ensure a new object is created for each element, which is what the Array.from() mapping function does.

The Traditional Method: The for Loop

The classic, imperative way to build an array is with a for loop. This method is straightforward, easy to understand, and correctly creates new objects for each element.

Solution:

const length = 3;
const newArray = [];

for (let i = 0; i < length; i++) {
newArray.push({ id: i + 1, key: 'value' });
}

console.log(newArray);

Output:

[ { id: 1, key: 'value' }, { id: 2, key: 'value' }, { id: 3, key: 'value' } ]
note

While more verbose than Array.from(), the for loop is a perfectly valid and readable alternative.

Conclusion

Creating an array of objects is a simple task with a clear best practice.

  • The Array.from({ length: N }, () => ({...})) method is the modern and recommended solution. It is concise, readable, and correctly creates a new, distinct object for each array element.
  • Avoid using Array.prototype.fill() with objects, as it will fill the array with references to the same object, leading to unintended side effects and bugs.
  • A traditional for loop is a perfectly valid and readable alternative to Array.from().