I am Hack Sparrow
Captain of the Internets.

The For Loop vs the For Each Loop in JavaScript

The For Loop vs the For Each Loop in JavaScript

When do you use the For Loop and the For Each Loop in JavaScript? The answers to that question depends entirely on your requirement. The For Loop is best for iterating over name-value pairs, and the For Each Loop best for iterating over values, for example arrays.

Neither is better or worse than the other, but understanding how they work will help you make the best use of them. Observe the examples below.

Note: The example code snippets require Firefox with the Firebug extension to run.

The For Loop

var o = {'name':'Batman', 'age':33, 'city':'Gotham City'};
for (var p in o) {
    console.log(p+': '+o[p]);
}

There's no way we can get the property name if we were to use the For Each Loop for the above object.

The For Each Loop

var animals = ['cat', 'dog', 'monkey', 'donkey'];
for each (var v in animals) {
    console.log(v);
}

We can accomplish the same thing as above using the For Loop, but the code would be not as simple and elegant. Here's how it would look like.

var animals = ['cat', 'dog', 'monkey', 'donkey'];
for (var p in animals) {
    console.log(animals[p]);
}

Notes and Tips

i. The For Loop is best for name-value pairs.
ii. The For Each Loop is best for iterable values. Eg: arrays, and objects if you are not interested in the name of the property.
iii. The For Loop can be used to explore the possible properties and methods of an object.

for (var p in document) { console.log(p + ': '+ document[p]); }

The above code will show all the properties and methods of the document object.

for (var p in window) { console.log(p + ': '+ window[p]); }

The above code will show all the available properties and methods of the window object.
iv. JavaScript global properties and methods are stored on the window object.

If you have got any questions or suggestions, post them in the comments section below.

Make a Comment