Iteration order of for.in – not by insertion (any more?)
According to my research, the order of keys in a for..in loop should be undefined/unreliable
Undefined, yes.
- but, if left undisturbed, should be in insertion order
No, you were right the first time: It's undefined. Even in ES2015 (aka "ES6") and above, which do provide property order for some other operations, the older operations for-in
and Object.keys
are not required to follow the order defined for the new ones.
In those other operations (Object.getOwnPropertyNames
, JSON.serialize
, ...), the order (defined here) isn't purely insertion order: Properties whose names are array indexes according to the spec's definition* come first, in numeric order. Most major JavaScript engines have updated their handling of for-in
to match their handling of these new operations (many already did treat array indexes differently, but they varied in terms of whether they put those before the non-array-indexes or after), but again, it's undefined, and you shouldn't rely on it.
If you want pure insertion order, ES2015's Map
provides that, regardless of the value of the key. Objects don't.
Here's an example using Map
:
const map = new Map([
['2', { name: 'bus', price: 10 }],
['3', { name: 'foot', price: 0 }],
['1', { name: 'taxi', price: 100 }]
]);
for (const entry of map.values()) { // bus, foot, taxi
console.log(entry.name);
}
* The spec's definition of an "array index" is:
An integer index is a String-valued property key that is a canonical numeric String (see 7.1.16) and whose numeric value is either +0 or a positive integer ≤ 253-1. An array index is an integer index whose numeric value i is in the range +0 ≤ i < 232-1.