I hope someone can correct me if i'm wrong about this
Inside the V8 source code array.js:1042, I found this:
for (var i = 0; i < length; i++) {
if (i in array) {
var element = array[i];
f(element, i, array);
}
//...
The important bit is the condition check using the 'in' operator to determine whether or not to execute the function argument passed into the forEach. The in operator checks for the existence of properties inside an object.
Now a JS array is simply a fancy object with numbered properties. Ie
var array = [undefined,undefined,undefined];
Object.keys(array); // ["0", "1", "2"]
Another way of thinking about the above array is by thinking of it as an object like this
{
"0": undefined,
"1": undefined,
"2": undefined
}
However if you use the other form for constructing the array, you get this:
var array2 = new Array(3);
Object.keys(array2); // []
This is why you will get the following result:
var array = [undefined,undefined,undefined];
var array2 = new Array(3);
array.forEach(function(){console.log('foo')}); //will print foo three times
array2.forEach(function(){console.log('bar')}); //will print nothing