Alex Rivera | Logout

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

Asked 2009-03-15T17:01:28.673
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

Edit
Report

1 Answer

0

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

answered 2009-03-15T17:04:32.083

Your Answer