16

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

Community
  • 1
  • 1
Julian Aubourg
  • 11,346
  • 1
  • 29
  • 29
  • possible duplicate of [Elements order - for (... in ...) loop in javascript](http://stackoverflow.com/questions/280713/elements-order-for-in-loop-in-javascript) – Borgar Jun 07 '11 at 19:36

2 Answers2

10

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.

chroder
  • 4,393
  • 2
  • 27
  • 42
  • 1
    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 Mar 15 '09 at 17:20
  • 1
    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. – chroder Mar 15 '09 at 17:39
0

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

Chetan S
  • 23,637
  • 2
  • 63
  • 78
  • 1
    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 Mar 15 '09 at 17:15
  • 1
    @Julian: the next edition 3.1 of ECMA-262 is less ambiguous: "The mechanics and order of enumerating the properties [...] is not specified." – Christoph Mar 15 '09 at 20:47