Difference between forEach and for loop in javascript
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:
- Performance: According to JsPerf : forEach is little slower than for loop.
- 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.
- Readability: Using for loop makes code more readable than having forEach in code.
- Browser compatibility: forEach is Not supported in IE < 9 So that introduces some shim in our code.
My questions are:
- What are the advantages of forEach over for loop ?
- In what scenarios, forEach is more preferable.
- Why did even it come into JavaScript ? Why was it needed at all ?
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.
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.
>> 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
.
In simple terms, according to the below article, and research, it seems that the main differences are:
For Loop
- It’s one of the original ways of iterating over arrays
- It’s faster
- You could
break
out of it using this keyword - In my opinion its mainly used for calculations with integers (numbers)
- The parameters are
(iterator, counter, incrementor)
ForEach Loop
- It’s a newer way with less code to iterate over arrays
- Easier to read
- Lets you keep variable within the scope
- Lower chance of accidental errors with the
i <= >= etc.....
- The parameters are
(iterator, Index of item, entire array)
forEach
- forEach is a method on the Array prototype.
- It is easy to use
- It contains a callback function and each element from array is passed to callback function
- Because of callback, You can not use await with forEach ,it will lead to different output than expected.
- Because of callback function it is slower than for loop
- Because of callback you can not use break
For loop
- In for loop you need an index, condition and increment/decrement of index variable
- It is faster than foreach
- You can use break
- It works with await
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> ]
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;
}
}
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.
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:
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.