views:

527

answers:

2

In php, if you have the following code:

$map = array(
  "first" => 1,
  "second" => 2
);

$map["third"] = 3;

foreach($map as $key => $value) {
  // code
}

You know the entries will be listed in the order they have been added to the array.

Now, can I assume the same rule applies to the Javascript equivalent below?

map = {
  "first": 1,
  "second": 2
};

map["third"] = 3;

for (key in map) {
  // code
}


This is a duplicate of: Elements order - for (… in …) loop in javascript

+1  A: 

No, the behavior depends on implementation and it is not guaranteed. Use an array when the order needs to be preserved.

Chetan Sastry
Yes but (in the standard):"The mechanics of enumerating the properties (step 5 in the first algorithm, step 6 in the second) is implementation dependent. The order of enumeration is defined by the object."So enumeration itself is implemtation dependent, but the order is object dependent, no?
Julian Aubourg
@Julian: the next edition 3.1 of ECMA-262 is less ambiguous: "The mechanics and order of enumerating the properties [...] is not specified."
Christoph
+1  A: 

Most browsers will loop through the properties in the order they were added to the object, but the Javascript standard says the order is undefined -- so you shouldn't rely on this behavior. For example, I read a blog post a while back about how Google Chrome didn't always exhibit this behavior.

If you need the ordered functionality, you should create a new class for yourself that can use both object or numeric keys.

Christopher Nadeau
Thanks a lot for the link. What John says is that, though it is not standard, browser vendors apply it as if it was (so the Chrome team will fix the "bug").
Julian Aubourg
Yup. Though I still don't think you should rely on the behavior. Safer to just create a custom class where you can define the behavior yourself.
Christopher Nadeau