Iterating in JavaScript

There are many, many ways to iterate in JavaScript.

Here is a brief examination of several of them.

For Loops #

Perhaps a controversial opinion: for loops are ugly. They contain a lot of boilerplate code that adds little to your code.

But they are effective, and versatile. They are the equivalent of using a sledge hammer to pound in a nail: it does the job, it’s not pretty, and it takes more energy than is strictly required. Take a look at what I mean:

var fruits = ['apple', 'orange', 'banana'];
for (var i = fruits.length - 1; i >= 0; i--) {
console.log(fruits[i]);
}

This is what we call an "Improved Native For Loop". It loops through your array in reverse, because that gives us several (admitably small) performance gains.

But it's so ugly. Yes it works well, but it's dense and hard to read. This code says "console log everything in this array", but to a beginner, it's hard to interpret it that way.

Let’s look at a few alternatives to traditional for loops, and maybe we can choose something that better suits our purposes in the future.

Looping Through Arrays #

var fruits = ['apple', 'orange', 'banana'];
fruits.forEach(fruit => {
console.log(fruit);
});

ForEach is strictly better than the for loop for many applications. It's much easier to read, and it's much harder to break. On top of that, it's much easier for other developers to read your code when you use a forEach loop. There's no configuration, what you see is what you get.

Main downsides: forEach is only available on native arrays in JavaScript. for loops you can use for anything, they are incredibly versatile. forEach loops are not that versatile.

forEach loops also do not allow you to break out of them. So if you need to end a loop early, you'll have to use something else. It's unfortunate that there's this limitation in JavaScript, but there you have it.

do...while with Iteratables #

while loops have always scared me a bit, if I’m honest. Back when I started building websites, web browsers did not handle infinite loops as well as they do today. I would often crash my browser while trying to make a while loop work, and occasionally crash my whole computer. Not fun for a beginner.

Fortunately our web browsers handle it much better these days, so if you make a mistake, it isn’t a big deal. while loops remain somewhat intimidating to me, but in some circumstances they are a clean solution.

For example, take using a while loop with an iterator:

If you've never heard of iterators, join the club. I’ve rarely seen one used in the wild. It is a useful protocol in JavaScript though, and one that I think more people should use. If you want to learn more about them, the MDN has an excellent article for you.

Both Arrays and Strings come pre-packaged with built-in iterators, and they are especially nice to use with a while loop:

var testString = 'testing';
// create a new iterator
var testIterator = testString[Symbol.iterator]();
do {
// get the next value in the iterator
var result = testIterator.next();
console.log(result.value);
} while (!result.done) // check if the iterator is empty

Pretty clean. Pretty readable. Very reuseable. Not bad.

Looping Objects #

Objects are other animals entirely.

None of the above methods work on them. This is partially because objects don't have a set order, like strings and arrays do, so any sort of loop that involves an index is not going to work on them.

Fortunately for us, for loops for objects are much prettier than regular for loops. They're called for...in, and they look like this:

var fruits = {'apple': 1, 'orange': 4, 'banana': 2}
for (fruit in fruits) {
console.log(fruit);
// logs 'apple', 'orange', 'banana': the keys of the object
console.log(fruits[fruit]);
// logs 1, 4, 2: the values of the object
}

← Home

Changelog
  • Add inclusive lang checker, remove non-inclusive language from blog posts
  • Adds new post about iterating in JavaScript