1

Since every JavaScript developer should know, that an object's order is not guaranteed to be the same in all circumstances, we are told to use arrays (of objects) whenever the order of children is sensible.

But every time I inspect an (unordered) object in the browser's devtools, I realize the order is exactly as I would expect it (assuming that JS objects behave like ordered maps).

When or why may the order of the properties change?

In different browsers/JS-interpreters? At different runtimes because of some memory optimizations, that I don't have any clue of?

Can anybody clarify, when the order of the object's property may change?

EDIT:

I have read the questions

But I cannot find information about when it is not safe to rely on the order.

ILCAI
  • 1,164
  • 2
  • 15
  • 35
  • 1
    Yes, every engine is free to implement `for … in` loops however it wants to. The order might be anything that suits the engine, e.g. sorting by alphabet or sorting by creation time, or preferring integer-indexed properties. (The last optimisation is done by most state-of-the-art engines and got standardised for certain operations in ES6) – Bergi Jan 12 '19 at 20:49
  • Thank you, Bergi. Do you have a link to a proposal or (official) documentation saying this? – ILCAI Jan 12 '19 at 20:52
  • 1
    It's unclear what you mean by "*when*". The answer would be "at any time, anywhere, when you don't deal with a restricted environment". If you happen to work with only a single engine, plan on never updating its version, and have documents on how property order was implemented there, then you can of course rely on the order being and staying consistent. But the web as a target environment for your code is no such place. – Bergi Jan 12 '19 at 20:54
  • You can find links to the official standard, and links to documentation about common engines, in the answers to the duplicates. – Bergi Jan 12 '19 at 20:55
  • Alright, thanks again for the info and pointing out the links in the duplicate questions. You helped me understand. BTW: By "when" I meant: which browser/engine or if a browser/engine can also change the orders at runtime, etc. But this information is irrelevant, knowing that every engine may sort by different criteria, like you have said. – ILCAI Jan 12 '19 at 21:01
  • I had always imagined that an engine would change the layout of `{x, y}` and `{y, x}` into a common one, as it would technically be allowed by the rules. However current engines do not do it and hardly will ever do it because of backwards compatibility (too many people did mistakenly rely on an order, and no browser vendor wants to break their code) and the latest ES6 rules. Other than that, I can't think of a case where it would be useful to change ordering strategy at runtime. – Bergi Jan 12 '19 at 21:16

0 Answers0