Difference between forEach and for loop in javascript
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)
https://alligator.io/js/foreach-vs-for-loops/
>> 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
.
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.