forEach on array of undefined created by Array constructor

Array(5) is essentialy equivalent to

var arr = []; 
arr.length = 5;

In javascript changing array’s length doesn’t set any values for it’s numeric properties nor does it define those properties in the array object. So numeric properties are undefined instead of having undefined value. You can check it by using:

Object.keys(arr)

When iterating javascript iterates through numeric properties of the array, so if these don’t exist, there is nothing to iterate over.

You can check it by doing:

var arr = Array(5)

//prints nothing
arr.forEach(function(elem, index, array) {
    console.log(index);
});

arr[3] = 'hey'
//prints only 'hey' even though arr.length === 5
arr.forEach(function(elem, index, array) {
    console.log(index);
});

The following code:

var arr = [undefined, undefined];

creates and array of length ===2 and sets the both numeric properties 0 and 1 to undefined.

Leave a Comment