25

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
  • 10
  • 23
Sachin Jain
  • 21,353
  • 33
  • 103
  • 168
  • 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 Jain Sep 23 '14 at 15:53

9 Answers9

22

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,100
  • 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
  • 32,681
  • 5
  • 61
  • 85
  • 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 Jain 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,928
  • 7
  • 68
  • 105
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
  • 7,316
  • 1
  • 24
  • 20
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
  • 14,608
  • 25
  • 132
  • 189
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
  • 88
  • 1
  • 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
0

forEach is a method on Array prototype which intakes a function expression that it executes on each iteration and within this function, the current iterated item of the Array is passed as the first argument.

ForEach structure:

// Arrow function
forEach((element) => { /* … */ })
forEach((element, index) => { /* … */ })
forEach((element, index, array) => { /* … */ })

On the other hand, A for loop is a construct inherent to JavaScript language itself. For loop repeats until a specified condition evaluates to false. Arrays operations are one thing that can be used within this for loop body but not necessarily the only thing whereas forEach works only with Array.

For loop structure:

for ([initialExpression]; [conditionExpression]; [incrementExpression]) {
 /* statement */
}

For loop is slightly better than forEach in performance but it is advised to use forEach whenever it can for more readable code.

Oleg Barabanov
  • 2,468
  • 2
  • 8
  • 17
aadilraza339
  • 103
  • 3
0

From: Eric Sarrion's Book “JavaScript from Frontend to Backend.” :

The difference between the for() loop and the forEach() method

To show the difference between these two approaches (the for() loop and forEach() method), let’s introduce a new element in the array, at index 10, knowing that the last index used during the creation of the array was 4. We thus create a new element that is much further away than the current last element of the array. How will the array react to this enlargement?

// original array
var tab = ["Element 1", "Element 2", "Element 3", "Element 4", 
"Element 5"];

// adding a new element in the array, at index 10
tab[10] = "Element 9";
console.log("tab =", tab);

// display the array with a for() loop
console.log("Access to each element by a for() loop");
for (var i = 0; i < tab.length; i++) console.log("tab[" + i + "]=", tab[i]);

// display the array by the forEach() method
console.log("Access to each element by the forEach() method");
tab.forEach(function(elem, i) {
 console.log("tab[" + i + "]=", elem);
});

We add an element to the array using tab[10] = "Element 9", then display the contents of the array using the for() loop and then the forEach() method. The result is displayed in the following figure:

enter image description here

The display of the for() loop shows that the elements with indices 5 to 9 exist but are of value undefined, because effectively, no values have been inserted for these indices of the array. However, the indices 5 to 9 with their undefined values are displayed by the for() loop.

Conversely, the forEach() method provides the callback function indicated in parameters with only the array elements that have actually been affected in the array. This therefore avoids the elements at indices 5 to 9, which have not been assigned in the program.

H S W
  • 6,310
  • 4
  • 25
  • 36