How to Pre-Fill an Array with 0s in JavaScript?

Estimated read time 1 min read

To pre-fill an array with 0s in JavaScript, you can use the Array.fill method. The fill method allows you to fill all elements in an array with a specified value. Here’s an example of how to pre-fill an array with 0s:

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

In this example, we create a new array with 5 elements using the Array constructor, and then call the fill method on the array, passing in 0 as the value to fill the array with. The result is an array with 5 elements, all set to 0.

You can also pre-fill an array with 0s using a for loop. Here’s an example:

var array = [];
var length = 5;

for (var i = 0; i < length; i++) {
  array[i] = 0;
}

In this example, we create an empty array and use a for loop to fill the array with 0s. The length variable determines the size of the array, and the loop continues until the value of i is equal to length. The result is an array with length elements, all set to 0.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply