I'm interested in efficiently creating an array of a specific length using the Array()
constructor and then iterating over it.
According to the information on MDN:
If you pass only an integer between 0 and 232-1 (inclusive) as the argument to the Array constructor, it will return a new JavaScript array with the length set to that number. Any other argument will result in a RangeError exception being thrown.
For example, executing Array(5)
does indeed create an array with a length of 5.
var arr = new Array(5);
console.log(arr); // [undefined x 5]
console.log(arr.length); // 5
However, when attempting to iterate over the elements of this array using forEach
, nothing is logged to the console.
arr.forEach(function(v, i) { console.log(v, i); });
// nothing logs to the console
In contrast, if I use an array literal and loop over the values, the expected output is logged:
[undefined, undefined].forEach(function(v, i) { console.log(v, i); });
// undefined 0
// undefined 1
Why does the forEach loop not work with arrays created by the Array constructor?
This answer sheds some light on the peculiar behavior observed with map
, for instance:
arr.map(function(v, i) { return i; }) // returns [undefined x 5]
However, my main focus is on understanding why the forEach
loop fails to iterate over the values at all.