Published 2020-08-17 by Daniel Bark
3 bad use cases of Javascript forEach loop
The forEach loop is part of most JS developers tool belt. But does it have to be? I would say no. I have yet to discovered a situation where forEach is the only reasonable solution and I find myself using it less and less. Some developers like the readability of a forEach loop and that can be a valid point since it’s a subjective matter. Personally I think that the “for of” loop is even more readable.
elements.forEach(function (el) {
// code
});
for (el of elements) {
// code
}
Let’s get into the situations where the forEach loop is just a bad fit.
If you want to short circuit or break out of the loop
Short-circuiting means terminating or skipping an iteration of the loop. In a forEach loop the only way to terminate the loop is to throw an exception. Because of this limitation you should expect a runtime matching linearly to the size of the looped array. As an example, searching for an element is therefore not a good use case for a forEach loop. Instead go for array methods ‘find’, ‘findIndex’ or a for loop which you can terminate.
When performance is critical
In the forEach loop, we are invoking the callback function on every iteration. This additional scope leads to slower speeds compared to the for loop. The for loop uses an initializing statement and a conditional that is evaluated at every iteration. That means lowered cost compared to the forEach.
It’s hard to say the exact numbers here since it varies per platform but I have seen performance differences from 2x up to 20x. Also there are performance improvements you can make to both for and forEach. One example being the “backwards for loop” where the conditional does not need to include an array.length check.
When you want to transform an array
For transformations you can use map and filter which both returns a new array. The forEach loop always returns undefined. To achieve the same result using forEach is more clunky.
Shout out to reduce for when you want to get an accumulate value by looping.
Hope you learned something reading this article and I wish you fun future coding sessions 🚀
Written by Daniel Bark
← Back to blog