Julian Aubourg
Julian Aubourg

Reputation: 11436

Is the order of fields in a javascript object predictable when looping through them?

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

Upvotes: 16

Views: 7554

Answers (2)

chroder
chroder

Reputation: 4463

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.

Upvotes: 10

Chetan S
Chetan S

Reputation: 23813

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

Upvotes: 0

Related Questions