A Better Way to Loop Over an Array

Joe Eames
Joe Eames
Feb 7 · 3 min read

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


Top Quality Tutorials

Joe Eames

Written by

Joe Eames

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


Top Quality Tutorials

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade