Javascript for in Loop Enumeration Order

Problem

When enumerating the properties of an object, ECMAScript specs doesn’t provide an explicit order. Instead it says the order is implementation dependent. Therefore the following code could result in different output from different browsers.


var pairs = {"c":"c","2":2,"b":"b","1":1, "a":"a"};
var result="";
for(var key in pairs)
{
 result += pairs[key] + ",";
}
alert(result);

Most of the browsers today will output “1,2,c,b,a”. But be aware of two things here:

  1. In Chrome, FireFox and IE, as of today, the “numerical” keys are order in numeric order and all others are ordered based on the when the property is defined; but other browsers may have different result;
  2. And there is no guarantee the same browser of different version (remember that your web site reader may have any version) will output the same result.

Solution

If your code needs to access the property values in a certain order (for example, the defining order), it is better to use array and index based enumeration.


var pairs = ["c",2,"b",1, "a"];
var result="";
for(var i = 0; i < pairs.length; i++)
{
 result += pairs[i] + ",";
}
alert(result);

Note that the index i is used above and it will guarantee to output “c,2,b,1,a”.

Further discussion

If you use for …in to access the array, all the array’s property (own and inherited) will be enumerated. This could lead to undesired result if a property is added via Array’s prototype.

Array.prototype.d = "d";
var pairs = ["c",2,"b",1,"a"];
var result="";
for(var i in pairs)
{
 result += pairs[i] + ",";
}
alert(result);

 

The output of the above code will be  “c,2,b,1,a,d“. If you want to filter out the inherited property, the function hasOwnProperty can be used.

...
for(var i in pairs)
{
 if(pairs.hasOwnProperty(i))
    result += pairs[i] + ",";
}
...

Advertisements
This entry was posted in Javascript & html, Programming and tagged , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s