To create an array filled with zeros, follow the following steps:
Create an empty array using the Array()
constructor.
let arr = new Array(length);
After that, call the fill()
method on the array and pass 0 to it.
arr.fill(0);
In this way, you create a zero-filled array in JavaScript.
let arr = new Array(5); arr.fill(0); console.log(arr); //[0, 0, 0, 0, 0]
The Array() constructor accepts an argument that is the number of empty elements the array should have.
console.log(new Array(5)); //[, , , ,]
If you don't want to use the Array()
constructor, create an empty array using the square brackets and set its length
property.
let arr = []; arr.length = 5; console.log(arr); //[, , , ,]
The value passed to the fill() method is assigned to each array element.
Alternatively, you can use for
loop to create a zero-filled array.
Start by creating an array with the desired number of empty elements. Then, call for
loop to iterate through the array. On each iteration, assign zero to the array element at the specific index.
let arr = new Array(5); for(let i=0; i<arr.length; i++){ arr[i] = 0; } console.log(arr); //[0, 0, 0, 0, 0]