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

1

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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").
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.
0

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

2 Comments

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: the next edition 3.1 of ECMA-262 is less ambiguous: "The mechanics and order of enumerating the properties [...] is not specified."

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.