JavaScript for…in vs for

JavaScript for…in vs for

Do you think there is a big difference in for…in and for loops? What kind of “for” do you prefer to use and why?
Let’s say we have an array of associative arrays:
var myArray = [{‘key’: ‘value’}, {‘key’: ‘value1’}];

So we can iterate:
for (var i = 0; i < myArray.length; i++) And: for (var i in myArray) I don't see a big difference. Are there any performance issues?


Solution 1:

The choice should be based on the which idiom is best understood.

An array is iterated using:

for (var i = 0; i < a.length; i++)
   //do stuff with a[i]

An object being used as an associative array is iterated using:

for (var key in o)
  //do stuff with o[key]

Unless you have earth shattering reasons, stick to the established pattern of usage.

Solution 2:

Douglas Crockford recommends in JavaScript: The Good Parts (page 24) to avoid using the for in statement.

If you use for in to loop over property names in an object, the results are not ordered. Worse: You might get unexpected results; it includes members inherited from the prototype chain and the name of methods.

Everything but the properties can be filtered out with .hasOwnProperty. This code sample does what you probably wanted originally:

for (var name in obj) {
    if (, name)) {
        // DO STUFF

Solution 3:

FYI – jQuery Users

jQuery’s each(callback) method uses for( ; ; ) loop by default, and will use for( in ) only if the length is undefined.

Therefore, I would say it is safe to assume the correct order when using this function.


$(['a','b','c']).each(function() {
//Outputs "a" then "b" then "c"

The downside of using this is that if you’re doing some non UI logic, your functions will be less portable to other frameworks. The each() function is probably best reserved for use with jQuery selectors and for( ; ; ) might be advisable otherwise.

Solution 4:

there are performance differences depending on what kind of loop you use and on what browser.

For instance:

for (var i = myArray.length-1; i >= 0; i--)

is almost twice as fast on some browsers than:

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

However unless your arrays are HUGE or you loop them constantly all are fast enough. I seriously doubt that array looping is a bottleneck in your project (or for any other project for that matter)

Solution 5:

Note that the native Array.forEach method is now widely supported.

Solution 6:

Updated answer for 2012 current version of all major browsers – Chrome, Firefox, IE9, Safari and Opera support ES5’s native array.forEach.

Unless you have some reason to support IE8 natively (keeping in mind ES5-shim or Chrome frame can be provided to these users, which will provide a proper JS environment), it’s cleaner to simply use the language’s proper syntax:

myArray.forEach(function(item, index) {
    console.log(item, index);

Full documentation for array.forEach() is at MDN.