The forEach
method iterates over the indices of the array. Interestingly enough, when you create a new array via new Array(n)
, it contains no indices at all. Instead, it just sets its .length
property.
> var a = new Array(3);
> console.info(a)
[]
> console.info([undefined, undefined, undefined])
[undefined, undefined, undefined]
MDN describes forEach
, and specifically states:
forEach executes the provided callback once for each element of the array with an assigned value. It is not invoked for indexes which have been deleted or elided.
Here's a neat technique to get an array with empty, but existing, indices.
var a = Array.apply(null, Array(3));
This works because .apply
"expands" the elided elements into proper arguments, and the results ends up being something like Array(undefined, undefined, undefined)
.