How to Fill an Empty Array in JavaScript?

Estimated read time 1 min read

You can fill an empty array in JavaScript by using a loop such as for or while to add elements to the array, or by using the Array.prototype.fill() method to fill the array with a specific value.

Here’s an example using a for loop:

const emptyArray = [];

for (let i = 0; i < 5; i++) {
  emptyArray.push(i);
}

console.log(emptyArray); 
// Output: [0, 1, 2, 3, 4]

Here’s an example using the Array.prototype.fill() method:

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

console.log(emptyArray); 
// Output: [0, 0, 0, 0, 0]

Note: In the second example, the Array.prototype.fill() method fills the array with the given value (0) for the number of elements specified by the length of the array (5).

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply