Create a Zero filled Array in JavaScript

avatar

Borislav Hadzhiev

Sun Nov 07 20212 min read

banner

Photo by Chewy

Create a Zero filled Array in JavaScript #

Use the fill() method to create an array filled with zeros, e.g. new Array(3).fill(0), creates an array containing 3 elements with the value of 0. The fill() method sets the elements in an array to the provided value and returns the modified array.

index.js
const arr1 = new Array(3).fill(0); console.log(arr1); // ๐Ÿ‘‰๏ธ [0, 0, 0]

The only parameter we passed to the Array() constructor is the number of empty elements the array should contain.

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

You can imagine that using the Array constructor is like creating an empty array and setting its length.

index.js
const arr = []; arr.length = 3; console.log(arr); // ๐Ÿ‘‰๏ธ [ , , ]

Either way we are creating an array with 3 empty elements.

The next step is to call the fill() method on the array.

The only parameter we passed to the fill method is the value we want to fill the array with.

Each of the 3 elements in the array get assigned a value of 0.

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

Create a Zero filled Array using for loop #

To create a zero filled array, use the Array() constructor to create an array of variable length and use a for loop to iterate over the array. On each iteration, assign the element at the specific index to 0.

index.js
const arr2 = new Array(3); for (let i = 0; i < arr2.length; i++) { arr2[i] = 0; } console.log(arr2); // ๐Ÿ‘‰๏ธ [0, 0, 0]

We used the Array() constructor to create an array containing 3 empty elements.

The for loop allows us to iterate over the array and assign each empty element to zero.

This approach is definitely more verbose, however if you have to support Internet Explorer, it gets the job done. In any other case, I'd pick the fill() method as its purpose is the solution to the problem.

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