I recently discovered a new way to loop through an array in JavaScript that doesn’t use the standby Array.length property to determine the number of iterations:
var someArray = ["Dogs", "Cats", "Chickens"];
for (var a=0, o; o=someArray[a]; a++) {
document.write(o + ‘<br/>’);
}
Here is how it works. The initial expression part of the loop var a=0, o sets the initial value of a to zero, which is the first element in our array and at the same time initializes a variable named o. The o variable is important as it will eventually hold the individual elements from our array as we iterate through it.
The next part of the loop - the conditional - is probably different from the traditional condition used when iterating through a loop. Most texts have you test the the counter or iterator value against the total number of elements in the array. This normally look like a<someArray.length
In my example, we are assigning an element of the array into the o variable that was initialized in the initial expression. The element that is assigned, is based on the current value of the counter variable a. As long as there is an element in the array at the counter value, JavaScript evauates the for loop’s conditional statement as true, and the loop’s statement block executes. The best part here and in my opinion the clever aspect of this method, is that the variable o now contains the value of the array and can be used in the loop statement block without having to re-resolve the array element value.
The loop also performs quite well as JavaScript does not have to evaluate someArray.length each iteration through the loop. In fact I performed a few benchmark tests on the various versions of this loop and for iterations under 1000 the methods perform equally well. When I bump up the iterations to 10000 or more, the method I’ve described in this article, performs up to twice as fast!
I’ve also seen versions of this loop -
for (var a=0, len=someArray.length; a<len ; a++)
- where the array length is only evaluated once. This method performs slower in my benchmarks than the method described in this article.
One note here, this method is not appropriate for looping through arrays that contain either numbers or boolean values, as assigning the number 0 into a variable resolves as false in the conditional part of the loop.