Does the "for…in" loop in Javascript loop 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?
From the ECMAScript Language Specification, section 12.6.4 (on the
for .. in
loop):And section 4.3.3 (definition of "Object"):
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.
Quoting John Resig:
All browsers respect definition order with the exception of Chrome and Opera which do for every non-numerical property name. In these two browsers the properties are pulled in-order ahead of the first non-numerical property (this is has to do with how they implement arrays). The order is the same for
Object.keys
as well.This example should make it clear what happens:
The technicalities of this are less important than the fact that this may change at any time. Do not rely on things staying this way.
In short: Use an array if order is important to you.