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.

✌️ Like this article? Follow @attacomsian on Twitter. You can also follow me on LinkedIn and DEV. Subscribe to RSS Feed.

👋 If you enjoy reading my articles and want to support me to continue creating free tutorials, ☕ Buy me a coffee (cost $5).