views:

2887

answers:

5

Does the for...in loop in Javascript loops through the hashtables/elements in the order they are declared? Is there a browser which doesn't do it in order?

The object I wish to use will be declared once and will never be modified.

Suppose I have:

var myObject = { A: "Hello", B: "World" };

And I further use them in:

for (var item in myObject) alert(item + " : " + myObject[item]);

Can I expect 'A : "Hello"' to always come before 'B : "World"' in most decent browsers?

+6  A: 

The elements of an object that for/in enumerates are the properties that don't have the DontEnum flag set. The ECMAScript, aka Javascript, standard explicitly says that "An Object is an unordered collection of properties" (see http://www.mozilla.org/js/language/E262-3.pdf section 8.6).

It's not going to be standards conformant (i.e. safe) to assume all Javascript implementations will enumerate in declaration order.

Adam Wright
+10  A: 

From the ECMAScript Language Specification, section 12.6.4 (on the for .. in loop):

The mechanics of enumerating the properties is implementation dependent. The order of enumeration is defined by the object.

And section 4.3.3 (definition of "Object"):

It is an unordered collection of properties each of which contains a primitive value, object, or function. A function stored in a property of an object is called a method.

I guess that means you cant rely on the properties being enumerated in a consistent order across JavaScript implementations. (It would be bad style anyway to rely on implementation-specific details of a language.)

If you want your order defined, you will need to implement something that defines it, like an array of keys that you sort before accessing the object with it.

Tomalak
+16  A: 

Quoting John Resig:

Currently all major browsers loop over the properties of an object in the order in which they were defined. Chrome does this as well, except for a couple cases. [...] This behavior is explicitly left undefined by the ECMAScript specification. In ECMA-262, section 12.6.4:

The mechanics of enumerating the properties ... is implementation dependent.

However, specification is quite different from implementation. All modern implementations of ECMAScript iterate through object properties in the order in which they were defined. Because of this the Chrome team has deemed this to be a bug and will be fixing it.

It's theory vs. praxis. In theory the property order cannot be trusted, but in practice it can.

Borgar
+2  A: 

in IE6, the order is not guaranteed.

+1  A: 

The order cannot be trusted. Both Opera and Chrome return the list of properties unordered.

<script type="text/javascript">
var username = {"14719":"A","648":"B","15185":"C"};

for (var i in username) {
  window.alert(i + ' => ' + username[i]);
}
</script>

The code above shows B, A, C in Opera and C, A, B in Chrome.

Kouber Saparev