A Better Way to Loop Over an Array

Joe Eames
Thinkster.io
Published in
3 min readFeb 7, 2020

When you need to loop over an array in JavaScript do you default to the trusty for loop? Even got yourself a quick keyboard macro to create your for loop? You’re in good company, I do the same. Something like the following is my habitual goto when looping over an array of data:

But there’s a better way. the forEach method on arrays not only lets you deal with this pattern in a more functional way, it’s just prettier (no relation to prettier :)

But what if you need the index? what if you’re going to display that as well, like in the following?

Well, no problem. foreach has you covered there. The second parameter to the foreach is the current index.

Finally, foreach allows you to separate out your iteration function from the iteration itself and create code that is extremely readable.

You CAN do this with a for loop, but it’s not nearly as readable:

One final note. The forEach function also uses a 3rd parameter which is the array itself, in case you need to use the entire array in your processing function.

Now it’s time to actually LEARN something. Without practice, tomorrow you’ll only remember about 15% of what you just read. Want to learn all of it? That requires actually PRACTICING what I just showed you.

This StackBlitz project has several different for loops that need to be turned into more readable foreach functions. It’ll take you a couple minutes to complete, but by the time you’re done you’ll actually feel comfortable using forEach in your own coding, and can finally drop that less effective for loop.

Happy coding!

Signup for my newsletter here.

Visit Us: thinkster.io | Facebook: @gothinkster | Twitter: @GoThinkster

--

--

Joe Eames
Thinkster.io

Mormon, Christian, Father, CEO of Thinkster.io, Organizer of @ngconf, @frameworksummit, React Conf. Front end developer, and Software Craftsmanship Evangelist.