How to populate an array with zeros or objects in JavaScript

published: 01 Apr 2022

2 min read

How to populate an array with zeros or objects in JavaScript

In JavaScript, you can use the Array.fill() method to populate an array with a zero or any other value like an object or a string. This method replaces all elements in an array with the value you want to populate the array with and returns the modified array.

For example, if you want to create an array with five slots and populate it with 0, you can do the following:

const array = new Array(5).fill(0);

console.log(array);

// [0, 0, 0, 0, 0]

You can also specify the position of where to start (default 0) and end (default array.length) the filling. By default, all elements will be filled. Here is an example that specifies filling positions:

const fruits = ['🍕', '🍔', '🍰', '🍩', '🍣'];

const filled = fruits.fill('🎂', 2, 4);

console.log(filled);

// ['🍕', '🍔', '🎂', '🎂', '🍣']

The Array.fill() method works great for JavaScript immutable values like strings, numbers, and booleans. What if you want to fill an array with objects?

const filled = new Array(3).fill({ pizza: '🍕' });

console.log(filled);

// [{ pizza: '🍕' }, { pizza: '🍕' }, { pizza: '🍕' }]

The above example populates an array with objects, but each slot in the array refers to the same object. So if you modify the object like below:

filled[0].pizza = '🍰';

It will update every object in the array because they are all referencing to the same object:

[{ pizza: '🍰' }, { pizza: '🍰' }, { pizza: '🍰' }]

To fill an array with objects, you should rather use the Array.from() method. This method creates a new array from an array-like or iterable object:

const filled = Array.from({ length: 3 }, () => ({ pizza: '🍕' }));

filled[0].pizza = '🍰';

console.log(filled);

// [{ pizza: '🍰' }, { pizza: '🍕' }, { pizza: '🍕' }]

Browser compatibility

The Array.fill() method is part of ES6 and only works in modern browsers. However, you can use a polyfill to support old browsers like Internet Explorer.

To learn more about JavaScript arrays and how to use them to store multiple pieces of information in one single variable, take a look at this article.

How to populate an array with zeros or objects in JavaScript | Coding Tips And Tricks

Are we missing something?  Help us improve this article. Reach out to us.

Are you looking for other code tips?

Check out what's on in the category: javascript, programming
Check out what's on in the tag: javascript, programming, array