Craig Gidney
Craig Gidney

Reputation: 18296

Does javascript guarantee that enumerating the same object twice will go over the fields in the same order?

When iterating over an object's members with a for .. in loop, the enumeration order is implementation defined. But, assuming the object is not modified, is iterating over it twice in the same browser during the same page visit guaranteed to give the same order?

Here is sample code that tests the property I'm talking about. The question boils down to whether or not a browser may throw "not the same":

a = []
b = []
for (var e in obj)
    a.push(e);
for (var e in obj)
    b.push(e);

// Are a and b's contents now the same?
// Or is the same-ness implementation defined?
for (var i = 0; i < a.length; i++)
  if (a[i] !== b[i])
    throw "not the same";

I'm interested in the answer both according to spec and in practice on existing browsers.

To be clear, I am not asking whether the order is consistent across browsers. I am asking if the order is consistent across multiple enumerations of the same object, within the context of a single visit to a web page and when the object is not being modified.

Upvotes: 3

Views: 127

Answers (1)

Quentin
Quentin

Reputation: 944076

No. It is, as the documentation says, implementation dependant. It is unlikely that an implementation would return the same object in a different order if it wasn't modified, but there is no guarantee.

A Set object, on the other hand, will "iterate its elements in insertion order".

Upvotes: 2

Related Questions