DEV Community

Devin Golden
Devin Golden

Posted on

For Loops vs. forEach: A Far Reach!

One of the major concepts that was reiterated over and over when I was first learning about Javascript arrays is that when we need a function to hit every object in an array, we need a loop.

Brother, may I loop thru an array?

brother loops

So in a world where we are designing an app that needs to go through a list of kitties (hopefully my future career), a typical for loop would look like this:

kitty loop

This works great, but we also have the option of using a nifty method that our array will inherit from Array.prototype called forEach(). We can invoke forEach() to effectively do the same thing that our for loop accomplished, and it will look a little something like this:

kitty forEach

I know what you're thinking, "Why would a developer prefer to use one over the other? Are there advantages and disadvantages of each??".
Well boy do I have a treat for you, because there absolutely ARE.

The Case for Loops

There are some real Joseph Gordon Levitt style Loopers out there that will tell you that for loops are much more efficient than using the forEach method, and they make some good points!

  • Some Javascript engines and browsers are more optimized for for loops.
  • Break can be used to terminate the loop early.
  • Gives more control over the conditions of the loop.

The forEach() Rebuttal

On the other hand, proponents of forEach() will be quick to tell you that the "forEach() method is #1!!" (this happens to me on the street all the time). I understand the passion that forEachers™️ have for their favorite Array method.

  • forEach is much more readable. When you factor in the temporary variables that are needed in for loops, it makes for a lot of code to look at! forEach looks cleaner and takes less time to read.
  • Less chance for small errors in code since you don't have to specify a condition statement.

The Dev Take!

While I really don't want to catapult myself into this debate, and I typically avoid talking politics, I have to say that I do have a preference here...

I think that in most circumstances where an array needs to be looped through, the forEach() method is better practice! It looks a lot nicer and makes code more readable and maintainable. One of the only times I would use a for loop is if I knew I needed to break out of the loop early. Otherwise, I go forEach() every time.

Bring on the hate mail from "for loopers".

loop earth

Latest comments (0)