JavaScript for vs. forEach
Resources: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for
https://alligator.io/js/foreach-vs-for-loops/ https://stackoverflow.com/questions/43031988/javascript-efficiency-for-vs-foreach
This is a bit of an odd post for me to be making. At my current company, and my company before this one, seeing a for
loop was almost impossible. It was like a white elephant. Are white elephants rare? Alright, finding a for
loop in the code base was like finding a zebra-striped elephant. If you think you saw one, you were probably under the influence. Nevertheless, for
loops are a foundational part of the language that is important to understand. And while forEach
certainly looks similar, the two are actually quite different.
To get a little technical, a for
loop is a "statement" whereas the forEach
is an Arry.prototype
method. Why is this important? The for
loop does not need to be attached to anything to be used. The forEach
needs to be called on an Array (to put it in broad strokes). That distinction will determine when we can use the two and when one might be preferable to the other.
Click here for a sandbox where you can run the code and see the output.
Let's take a look at the basic for
loop syntax
// Let's pretend we can't use fancy ES6+ stuff for this first one
var stopCounting = 5;
var count = 0;
console.log('before for loop: ', count);
for (var i = 0; i < stopCounting; i++) {
count += 1;
console.log('after increment: ', count)
}
console.log('final count: ', count)
There's nothing crazy going on here. There's a certain amount of boilerplate syntax we need to use to get things set up but then it's pretty basic, each time we go through the loop do this thing.
Let's compare that to the forEach
:
const ourArray = [1, 2, 3, 4, 5];
let count = 0;
let sum = 0;
ourArray.forEach((element) => {
count += 1;
console.log('after increment count: ', count);
sum += element;
console.log('after add element to sum: ', sum);
});
console.log('final count: ', count);
console.log('final sum: ', sum);
The example is meant to show two things.
- We can do the same as with our for loop, "for each thing (time) do this thing", and we increment our count by 1 each time
- The
forEach
method gives us access directly to the array element. We don't need to do anything likeourArray[i]
.
Overall it reads much cleaner, and it gives direct access to the elements as we iterate over them. When we're dealing with arrays we betterusing the elements for something, otherwise what do we need the array for?
Now I mentioned before how these two things are not interchangeable due to forEach
existing on Array.prototype
, so while we can't just swap them in and out whilly-nilly, when we have an array that we want to iterate over forEach
is a simpler, cleaner solution.
To wrap up:
for
andforEach
are similar but still very different in why we would use them. They help us iterate, but think right tool for the right job.for
is a basic JS statement and can be used anywhere you would use any another statementforEach
is attached toArray.prototype
which limits where you can use it more thanfor
- Prefer the
forEach
when you want to iterate over an array - Read the actual documentation linked at the top of this article to better understand both and all the additional details that go along with them. This has only been a very brief summary.