Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does JavaScript's forEach loop decide to skip or iterate through "undefined" and "null" elements in an Array?

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]?

like image 684
Aaditya Sharma Avatar asked Jul 29 '16 11:07

Aaditya Sharma


1 Answers

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.

like image 100
Aurora0001 Avatar answered Oct 05 '22 15:10

Aurora0001