Better JavaScript–Iterating Arrays

If you do JavaScript on a regular basis you probably end up iterating over arrays fairly often.  And if you’re anything like me you’re going to end up missing the foreach looping construct in C#.

Let’s declare the following array and then try to iterate over it.

var arr = ['A','B','C','D','E','F','G','H','I','J'];

The most common way of doing this is with a simple for loop.

for (var index = 0; index < arr.length; index++) {
    console.log("Item " + index + " is " + arr[index]);
}

You can also use the each method in jQuery.

$(arr).each(function (index, item) {
    console.log("Item " + index + " is " + item);
});

The downside here is that we’re declaring a new function and changing the context – the meaning of the keyword this will change – something which can get a bit annoying at times.

The default for loop is also a bit inefficient – you are looking up the length property on every loop.  A slight improvement is this:

for (var index = 0, len = arr.length; index < len; index++) {
    console.log("Item " + index + " is " + arr[index]);
}

An even nicer way is this:

for (var index = 0, item; item = arr[index++];) {
    console.log("Item " + (index-1) + " is " + item);
}

Although I’m not crazy about the index moving on before you can use it.  I think the easiest way is probably:

for (var index in arr) {
    console.log("Item " + index + " is " + arr[index]);
}

Interestingly enough if you add properties to Array.prototype they will also be iterated in this way.  While this is probably the easiest way to iterate over an array it’s also very inefficient – up to 20 times slower than a standard for loop.  Read more here.

So the best way of iterating over an array is probably a standard for loop where we cache the length property.  (Leaving out the caching may result in the loop being only half as fast as with the cached length)

for (var index = 0, len = arr.length; index < len; index++) {
    console.log("Item " + index + " is " + arr[index]);
}

I never thought I would write a blog about iterating an array – JavaScript is a really interesting little language.  Happy coding.