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

asked Mar 15, 2009 at 17:01
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.

answered Mar 15, 2009 at 17:12
2
  • 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"). Commented Mar 15, 2009 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. Commented Mar 15, 2009 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.

answered Mar 15, 2009 at 17:04
2
  • 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? Commented Mar 15, 2009 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." Commented Mar 15, 2009 at 20:47

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.