about 1 year ago

The functionality of the for loop and the forEach method of the array object are very similiar: looping through a list of items and do something with it. The differences lies below:

Break & Continue

You cannot break inside forEach:

var arr = [1,2,3,4,5];
arr.forEach(function(element, index){
    if (element === 3){
     break; // SyntaxError: Illegal break statement

  }
});

But you can simulate continue:

var arr = [1,2,3,4,5];
arr.forEach(function(element, index){
    if (element === 3){
     continue; // SyntaxError: Illegal continue statement

  }
  console.log(element);
});

arr.forEach(function(element, index){
    if (element === 3){
     return; // return will not break out of the forEach loop, it works like continue in this case

  }
  console.log(element);
});

// output:

1
2
4
5

Variable Scope

Another are where for loop and forEach differs, is the variable scope:

for(var i=0;i<5;i++){
}
console.log(i); // output: 5

Everything defined in a for loop belongs to its containing environment. But since forEach uses a function, you don't have to worry about variables leaking out of scope:

var arr = [1,2,3,4,5];
arr.forEach(function(element, index){
});
console.log(element); // ReferenceError: element is not defined

Performance

As being pointed out by this stackoverflow answer, for loop is faster than forEach. If you need to loop through tens of thousands of records, use the for loop (actually, generators maybe better for this scenario). Otherwise, forEach is a better choice as humans reading your code can easily understand your intension.

← Right shifting negative numbers in Javascript The new line character →
 
comments powered by Disqus