1024px-Flatirons_Winter_Sunrise_edit_2

Ways to loop over an array in JavaScript?

There are a multitude of ways to loop over an array in JavaScript; some common, some less so. Probably the most familiar ways to loop over an array in JavaScript are the for loop and the while loop; for/in loops will work as well, but are traditionally reserved for objects (and come with some additional issues). JavaScript arrays also inherit several methods for looping over an array from the Array prototype (Array.prototype.forEach() is a good example). Less conventionally, yet perhaps more interestingly, recursion can be used to loop over an array in JavaScript. And that’s not all… several more methods exist! For brevity’s sake, we won’t look at all the unique ways in which one is able to loop over an array in JavaScript. I will however, in the following text, give examples of each of the aforementioned means for looping over an array in JavaScript. We’ll start with a little Lil’ Jon… “Turn down for loop?”

For Loop

http://codepen.io/anon/pen/mVjLEK?editors=0012

While we’re at it…

While Loop

http://codepen.io/anon/pen/JGBvRN?editors=0012

Each and every element…
Array.prototype.forEach()

http://codepen.io/anon/pen/LGBmyO?editors=0012

Just for fun, ES6 arrow function syntax…

//I used to be an ES5 function like you. Then I took an arrow in the syntax…

http://codepen.io/anon/pen/wMxjrb?editors=0012

And finally, some function-ception…

Recursion

http://codepen.io/anon/pen/WrKJJN?editors=0012
There you have it! Four relatively straightforward ways to loop over an array in JavaScript; two more common, one Array prototype method, and some fun with recursion! We even threw in a bit of ES6 syntax for good measure. It’s my hope that you now have a good or at least better understanding of various ways in which you can loop over an array in JavaScript. Hopefully, none of the information featured above threw your for a… loop. 😉