2

Possible Duplicate:
Elements order - for (... in ...) loop in javascript

Assume you have code like this:

var a = {}
a.a = 1;
a.c = 2;
a.b = 3;

for (var i in a) {
    console.log(a[i]);
}

Are 1, 2, and 3 guaranteed to be printed in that order? I've tested and this has been the case so far, but I don't know if it'll always be true. Is there any browser which does not do this? There's nothing weird going on, like deleting things, prototype inheritance, etc. Just adding properties to an object.

Community
  • 1
  • 1
swampsjohn
  • 6,826
  • 7
  • 37
  • 42
  • 1
    This is a good question, but it's actually a duplicate: http://stackoverflow.com/questions/280713/elements-order-for-in-loop-in-javascript, question id 280713 – Paolo Bergantino May 28 '09 at 03:29

2 Answers2

3

All current browsers with the exception of Chrome will loop over the properties of an object in the same order as they were defined.

Here is the chrome bug report: http://code.google.com/p/chromium/issues/detail?id=883. It is currently marked as WontFix.

Crescent Fresh
  • 115,249
  • 25
  • 154
  • 140
  • From http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-357.pdf: The order in which item is bound to members of collection is implementation dependent. I guess it would be more appropriate to use an array when order is significant. – harto May 28 '09 at 03:34
  • @harto: nice link. That quote is actually referring to the newer "for each" loop construct, although there is a similar doc somewhere that says the same thing for "for in". Either way it's the reason V8 won't be "fixing" this anytime soon. – Crescent Fresh May 28 '09 at 03:39
  • @harto: in ecmascript 5 the order is defined as being the order of insertion – olliej May 28 '09 at 04:40
  • Google's attitude on this is uncharacteristically obstuctive - see bug comments 16 and 17 :) Hopefully ecma5 motivates them to "fix" this sooner rather than later. – annakata May 28 '09 at 08:53
  • ollieJ, the Ecmascript 5 standard I downloaded and skimmed seemed to say the opposite: that "The mechanics and order of enumerating the properties... is not specified." – user240515 Apr 07 '11 at 22:15
1

In my current version of Chrome (2.0.172.28) John Resig's test case passes, so maybe it is fixed in Chrome now?

user113611
  • 11
  • 1