1

Possible Duplicate:
Does JavaScript Guarantee Object Property Order?

I notice that in Javascript (on Chrome, at least) objects remember the order of their members. For example, in

var foo = { x: 1, y: 2 }
var bar = { y: 2, x: 1 }

foo and bar are distinguishable by the order the keys appear when I iterate over them.

My questions are:

  1. Is this behavior specified by the standard, or should it be considered an implementation detail?
  2. If it is specified by the standard, is there a way to change the order?
Community
  • 1
  • 1
luqui
  • 59,485
  • 12
  • 145
  • 204
  • What do you need to change the order for? – zerkms May 04 '12 at 08:04
  • @zerkms, seriously? My application uses a sorted dictionary where the sort order is modifiable. I can simulate it by storing the order alongside the dictionary, I was just wondering whether I needed to. – luqui May 04 '12 at 08:11

1 Answers1

3

Objects properties are not sorted. The behaviour is implementation-dependent.

However, most JS engines seem to keep the order that was used in an object literal nowadays.

V8/Chrome didn't do so some time ago though.

ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
  • Though it sounds correct, can you give a reference to an official source saying it? – gdoron May 04 '12 at 08:05
  • 1
    http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf - I'll add a better reference later, but with a dns-tunnel connection downloading that document will take some time. – ThiefMaster May 04 '12 at 08:10
  • Cool. **+1**. Didn't want vote on an answer that I wasn't sure is correct – gdoron May 04 '12 at 08:11
  • 1
    `An object is a member of the type 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.` – gdoron May 04 '12 at 08:12
  • 12.6.4: *The mechanics and order of enumerating the properties ... is not specified.* – ThiefMaster May 04 '12 at 08:21