23

I am wondering: Is there any significant difference between forEach and for loop in JavaScript.

Consider this example:

var myArray = [1,2,3,4];

myArray.forEach(function(value) {
  console.log(value);
});

for (var i = 0; i < myArray.length; i++) {
  console.log(myArray[i]);
}

Here is part of my research:

  1. Performance: According to JsPerf : forEach is little slower than for loop.
  2. Usability: There is no way we can break/return from the callback in case of forEach loop.

For example: You want to find out if a number is prime or not. I think using for loop is much more easier than using forEach loop to do this.

  1. Readability: Using for loop makes code more readable than having forEach in code.
  2. Browser compatibility: forEach is Not supported in IE < 9 So that introduces some shim in our code.

My questions are:

  1. What are the advantages of forEach over for loop ?
  2. In what scenarios, forEach is more preferable.
  3. Why did even it come into JavaScript ? Why was it needed at all ?
Pooja Kedar
  • 439
  • 2
  • 8
  • 23
Sachin
  • 20,754
  • 28
  • 93
  • 162
  • Well technically you can break out of a for each by throwing an error.... 1) Opinion 2) Opinion 3) Opinion. – epascarello Sep 23 '14 at 12:18
  • @Sirko—I think you mean `[1,2,,3,4]`. The array in your comment has five members, both *for* and *forEach* will visit all five. However, if one (or more) members don't exist (a so called "sparse" array) then *forEach* will not visit the missing members. – RobG Sep 23 '14 at 12:29
  • @RobG Right. Can't correct now. – Sirko Sep 23 '14 at 12:32
  • possible duplicate of [what is the difference between for and foreach](http://stackoverflow.com/questions/10929586/what-is-the-difference-between-for-and-foreach) – pjmorse Sep 23 '14 at 15:17
  • @epascarello Thanks for the suggestion of throw and catch....But it is just a workaround...I would still go by for loop. – Sachin Sep 23 '14 at 15:53

7 Answers7

21

forEach is a method on the Array prototype. It iterates through each element of an array and passes it to a callback function.

So basically, forEach is a shorthand method for the use-case "pass each element of an array to a function". Here is a common example where I think Array.forEach is quite useful, compared to a for loop:

// shortcut for document.querySelectorAll
function $$(expr, con) {
    return Array.prototype.slice.call((con || document).querySelectorAll(expr));
}

// hide an element
function hide(el) {
    el.style.display = 'none';
}

// hide all divs via forEach
$$('div').forEach(hide); 

// hide all divs via for
for (var divs = $$('div'), i = 0; i < divs.length; i++) {
    hide(divs[i])
}

As you can see, the readability of the forEach statement is improved compared to a for loop.

On the other hand, a for statement is more flexible: it does not necessarily involve an array. The performance of a normal for loop is slightly better, because there is no function call for each element involved. Despite of this, it is recommended to avoid for loops when it can be written as a forEach statement.

Lea Rosema
  • 1,060
  • 16
  • 31
20

In a forEach loop you don't control the way you iterate over the array. The classic for loop allows you to choose the iteration algorithm as you want (i++; i--; i+=2*i, etc).

However, a forEach loop is much easier to use - you don't need to mess with all the i counting, finding the array[i] object -- JS does it for you.

naivists
  • 31,708
  • 5
  • 57
  • 81
  • Thank you for the nice point..+1. It is really good point about loops that you can manipulate loop index according to your situation. For example: Printing even numbers. – Sachin Sep 23 '14 at 15:58
8
>> sparseArray = [1, 2, , 4];

>> sparseArray.forEach(console.log, console);
1 0 [1, 2, 3: 4] 
2 1 [1, 2, 3: 4] 
4 3 [1, 2, 3: 4] 

>> for(var i = 0; i < sparseArray.length; ++i) { console.log(sparseArray[i]) };
1
2
undefined
4 

forEach is a recent addition to make expressive list-comprehension style possible in javascript. Here you can see that forEach skips elements that were never set, but the best you can do with a for loop is to check for undefined or null, both of which can be set as values and picked up by forEach. Unless you expect missing values, forEach is equivalent to for loops, but note that you cannot stop early, for which you need every.

Phil H
  • 19,234
  • 7
  • 64
  • 103
2

In simple terms, according to the below article, and research, it seems that the main differences are:

For Loop

  1. It's one of the original ways of iterating over arrays
  2. It's faster
  3. You could break out of it using this keyword
  4. In my opinion its mainly used for calculations with integers (numbers)
  5. The parameters are (iterator, counter, incrementor)

ForEach Loop

  1. It's a newer way with less code to iterate over arrays
  2. Easier to read
  3. Lets you keep variable within the scope
  4. Lower chance of accidental errors with the i <= >= etc.....
  5. The parameters are (iterator, Index of item, entire array)

https://alligator.io/js/foreach-vs-for-loops/

Jonathan Sanchez
  • 4,331
  • 1
  • 20
  • 18
1

forEach

  1. forEach is a method on the Array prototype.
  2. It is easy to use
  3. It contains a callback function and each element from array is passed to callback function
  4. Because of callback, You can not use await with forEach ,it will lead to different output than expected.
  5. Because of callback function it is slower than for loop
  6. Because of callback you can not use break

For loop

  1. In for loop you need an index, condition and increment/decrement of index variable
  2. It is faster than foreach
  3. You can use break
  4. It works with await
Sunil Garg
  • 12,670
  • 19
  • 110
  • 153
0

Here is a difference between forEach and for loop in JavaScript.

Performance wise, I prefer the for loop over the forEach loop. This is just one of some issues I have come across with the forEach loop.

let abc = [1,2,3] 

abc.forEach((e) => { 
   delete e; 
}) 

console.log(abc)  //Array(3) [ 1, 2, 3 ]

for (let i = 0; i < abc.length; i++) { 
   delete abc[i]; 
} 

console.log(abc)  //Array(3) [ <3 empty slots> ]
Foz
  • 58
  • 6
0

Apart from flexibility, one main reason why I would use the for loop is if I needed to break out of a loop early.

In the below sample code if you wanted to only return a certain value in your array, you could use an if statement to check if your criteria matchs, and then break out from the loop. The forEach method would iterate over each food, which could lead to performance issues.

//Assume that foodArray has been declared
for (let i = 0; i < foodArray.length; i++) {
  if (foodArray[i].name === 'Pizza') {
    console.log('PIZZA EXISTS');
    break;
  }
}
Kayvan Salimi
  • 335
  • 2
  • 13