I know that forEach
method will iterate through an array object and will skip all array elements which are either null
or undefined
. I've an example below:
var a = [1,2,3,,5,6];
var b = [1,2,3,undefined,5,6];
var fn = function(arr){
arr.forEach(function(currentValue, index, array){
console.log(currentValue);
});
};
fn(a); //Prints on console (separated by newline): 1 2 3 5 6
fn(b); //Prints on console (separated by newline): 1 2 3 undefined 5 6
In above example,
fn(a)
is executed, the forEach
loop ignores the 4th element a[3]
which is undefined.fn(b)
is executed, the forEach
loop iterates through the 4th element b[3]
which is also undefined. What is the difference between a[3]
and b[3]
here? Why forEach
loop didn't skip b[3]
?
According to the specifications of ECMAScript 5.1, missing array items are elided.
Whenever a comma in the element list is not preceded by an AssignmentExpression (i.e., a comma at the beginning or after another comma), the missing array element contributes to the length of the Array and increases the index of subsequent elements. Elided array elements are not defined.
Since they are undefined, behaviour is unpredictable and there is no definition as to whether these should be treated as normal array items like undefined
. I suspect that in some browsers, undefined may be returned, but this doesn't appear to be the case in Chrome. Here's what your first example of [1, 2, 3,, 5, 6]
evaluates to:
[1, 2, 3, undefined × 1, 5, 6]
However, [1, 2, 3, undefined, 5, 6]
just evaluates to:
[1, 2, 3, undefined, 5, 6]
As we can see, these are subtly different, so the behaviour is not the same even though they look superficially similar.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With