Best Way to Loop Through an Array in JavaScript

Last week, a colleague of mine asked me “Why are you using a ‘standard for loop’ rather than the faster ‘for-in loop’ to loop through an Array in JavaScript?” and for this reason I’m going to write a short explanation about that.

First of all, when I talk about the standard ”FOR loop”, I mean something like

1
for (var i=0; i < myArray.length; i++){}

instead the ”FOR-IN loop” is something like:

1
for (var i in myArray){}

for-in loop is faster…just to type, for a lazy developer :) and it’s a common mistake especially for developers coming from Java programming (I’m a Java developer as well, that’s why I know that :P), trying to port Java into JavaScript.

The two main problems with for-in loop are : 1) It enumerates through all the properties even the ones associated to the Object (that can be augmented previously) 2) The order of the elements is not guaranteed.

You may not interested in the order of the elements(even if often you are), but you need to deal with the first issue and that’s what can happen:

1
2
3
4
5
6
7
8
9
var myArray = ["aa", "bb"];

// Object() augmented
Object.prototype.newMethod = "cc";

// for-in loop
for (var i in myArray) {
  console.log(myArray[i]); //"aa", bb", "cc"
}

The console will print not only the two elements from the array, but also the value of the new property in the Object. Remember that array are objects in JavaScript, at the root of the prototypal chain there is always Object and you never know if Object has augmented previously by a library or some script.

The correct way to execute that loop is using the for loop:

1
2
3
4
5
6
7
8
9
10
var myArray = ["aa", "bb"];

// Object() augmented

Object.prototype.newMethod = "cc";

//for loop
for (var i=0; i < myArray.length; i++) {
  console.log(myArray[i]); //"aa", "bb"
}

Actually, we can make a micro-optimization to this, “caching” the length of the array and avoiding every time to calculate the length of the array.

1
2
3
4
var myArray = ["aa", "bb"];
for (var i=0,  tot=myArray.length; i < tot; i++) {
  console.log(myArray[i]); //"aa", "bb"
}

Notice that there is a comma between “var i=0” and “tot=myArray.length” as the “for loop” accepts three expressions.

If you find this last way a bit weird, you could do something like:

1
2
3
4
5
6
var myArray = ["aa", "bb"],
  i=0;

for (tot=myArray.length; i &lt; tot; i++) {
  console.log(myArray[i]); //"aa", "bb"
}

So it’s strongly recommended to use the FOR LOOP to loop through an Array and remember that Java and JavaScript are different.

In the next post, I may go through where the “for-in” loop is used.

Comments