Using a for each loop on an empty array in JavaScript [duplicate]

You can use a forEach like you intended if you modify the array initialization to be:

var arr = Array.apply(null, Array(10))

And then you can do a foreach like:

arr.forEach(function(el, index) {
    arr[index] = 0;
});

The result is:

[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

Leave a Comment