8

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,

  • when fn(a) is executed, the forEach loop ignores the 4th element a[3] which is undefined.
  • But, when 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]?

Aaditya Sharma
  • 2,125
  • 1
  • 19
  • 34
  • 1
    Possible duplicate of [JavaScript 'in' operator for \`undefined\` elements in Arrays](http://stackoverflow.com/questions/22448330/javascript-in-operator-for-undefined-elements-in-arrays) – JJJ Jul 29 '16 at 11:54
  • 2
    The premise is just wrong: forEach won't skip elements that are null or undefined. It skips elements that don't exist at all. – JJJ Jul 29 '16 at 11:55
  • @JJJ is right. Try `[null, , undefined].forEach(console.log)`. It prints `null`, skips the index with no value, then prints `undefined`. – Web_Designer Jun 08 '17 at 21:04

2 Answers2

2

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.

Aurora0001
  • 10,827
  • 5
  • 47
  • 50
0

If you print the arrays in the console you will get:

var a = [1,2,3,,5,6];
var b = [1,2,3,undefined,5,6];
console.log(a);
console.log(b);

Console

    >[1, 2, 3, 4: 5, 5: 6]
    >
    0:1
    1:2
    2:3
    4:5
    5:6
    length:6


    >[1, 2, 3,undefined, 5,6]
    >
    0:1
    1:2
    2:3
    3:undefined
    4:5
    5:6
    length:6

So there are not element in index 3.

polamoros
  • 259
  • 1
  • 7