The for loop and forEach

The forEach and for loop can be used to accomplish effectively the same functionality for array. For example:

for (var i = 0; i < array.length; i++){ /* ... */ }

and

array.forEach(function(item, index){ /* ... */ });

Are there any difference between them?

The difference

The most substantive difference between the for loop and the forEach method are:

With for

  1. You may break out of the loop.
  2. You may use the continue to jump over iteration.
  3. The performance is much faster than forEach.
  4. The scope of the index, for example i, is scoped to the containing function:
    // 'i' is scoped to the containing function
    for (var i = 0; i < arr.length; i++) { ... }

With forEach

  1. You can simulate continue by simply returning from the function passed to forEach.
  2. However, there is no way to stop forEach looping altogether.
  3. The performance is much slower than for.
  4. The scope of the index, for example i, is scoped to the internal function:
    // 'i' is scoped to the internal function
    arr.forEach(function (el, i) { ... });
  5. However, forEach is more expressive. It represents your intent to iterate through each element of an array, and it provides you with a reference to the element, not just the index.

Performance Test

The performance test is run across a jsperf.com test of a for loop vs foreach.

Here is the performance difference when running test in Chrome 47 on Mac OS X:

The scope of the index difference in details

Let’s say that I would like to do something asynchronous with the elements of an array.

// The array:
var elements = ["element1", "element2", "element3"];

This is how it is supposed to be implemented usingforEach:

elements.forEach(function(element) {
  // The asynchronous action simulator
  setTimeout(function() {
    console.log(element);
  }, 100);
});

Without knowing about forEach() I would start with a classic for(;;) loop:

for (var i = 0; i < elements.length; i++) {
  setTimeout(function() {
     console.log(elements[i]);
  }, 100);
}

This doesn’t work as expected, because instead of element1, element2, and element3 on the console, I’m getting undefined three times. It seems that something is wrong with the i variable, because the function works fine with elements[0]. Actually, there is not nothing wrong with i. The thing is that its value is 3 when the console.log() is called and since elements[3] does not exist, it prints out undefined.

Reference & Resources

  • http://zsoltfabok.com/blog/2012/08/javascript-foreach/