3

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.

Community
  • 1
  • 1
Craig Gidney
  • 17,763
  • 5
  • 68
  • 136
  • 1
    what happens when you create a test case to try this out in different browsers? – George Stocker Mar 08 '16 at 21:08
  • 4
    Pretty sure this is undefined behaviour: you really shouldn't rely on it for correctness. – Chris Kitching Mar 08 '16 at 21:08
  • @GeorgeStocker In Chrome and Firefox, on the small objects I tested, the order was consistent. But because I can't think of any good behind-the-scenes reason for the order to change when the object isn't otherwise touched, that's not surprising to me. There may be interesting cases where it changes (e.g. many reads causing the JIT to switch to a different hashing strategy), but I didn't trigger any. – Craig Gidney Mar 08 '16 at 21:11
  • 2
    Personal anecdote-- iterating over performance timing object yielded the same properties in the same order, but specific to each browser. When attempting to iterate over the object in chrome vs firefox there were slight differences in the order in which the properties appeared – user2879041 Mar 08 '16 at 21:11

1 Answers1

2

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

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • A set that keeps track of insertion order? I thought we called that a list. Well well... – Alex Mar 08 '16 at 22:38
  • @Alex Membership testing is still cheap, and fast accessing-by-index isn't supported; so it's a fine Set. Having a consistent iteration order from the start is a good design idea because people have this nasty tendency of relying on implementation quirks even if you have docs saying they shouldn't. – Craig Gidney Mar 08 '16 at 23:02