Sub topic 5
The Order of Property Keys
This chapter assumes you already know how for...in walks an object's enumerable string keys, and that it also visits keys inherited through the prototype chain. You should also be comfortable with object literals, Object.keys, and Object.create.
A common belief is that JavaScript objects have no defined key order. That stopped being true years ago. ES2015 defined the order for Reflect.ownKeys and related internal operations. ES2020 then pinned down for...in for ordinary cases. The order is predictable, though it is often not the order you typed the keys in.
The rule in one sentence
An ordinary object lists its own keys in three groups:
- Integer-like keys (the spec calls them array indices) in ascending numeric order.
- All other string keys in the order they were created.
- Symbol keys in the order they were created.
for...in, Object.keys, Object.values and Object.entries never include symbols, so in practice you only see the first two groups.
const o = { b: 1, 2: 'two', a: 2, 1: 'one' };
console.log(Object.keys(o));
// ['1', '2', 'b', 'a']
for (const key in o) {
console.log(key);
}
// 1
// 2
// b
// a'1' and '2' come first, sorted as numbers. 'b' and 'a' follow in the order the literal created them. They are not sorted alphabetically.
What counts as "integer-like"
Property keys are always strings or symbols. When you write { 2: 'two' }, the key is the string '2'. A string key lands in the first group only if it is the canonical form of a non-negative integer, meaning String(Number(key)) === key, and its value is at most 2^32 − 2. That upper limit is the largest valid array index.
Strings that look numeric but fail that test go into the second group with the ordinary names:
const k = { '10': 'a', '9': 'b', '01': 'c', '-1': 'd', '1.5': 'e', name: 'f' };
console.log(Object.keys(k));
// ['9', '10', '01', '-1', '1.5', 'name']| Key | Integer-like? | Reason |
|---|---|---|
| `'9'`, `'10'` | Yes | Canonical non-negative integers |
| `'01'` | No | Leading zero, so `String(Number('01'))` is `'1'` |
| `'-1'` | No | Negative |
| `'1.5'` | No | Not an integer |
| `'name'` | No | Not numeric |
The integer-like keys sort as numbers, so '9' comes before '10'. A string sort would put '10' first. The rest keep their creation order.
Creation order, deletion and reassignment
"Creation order" means the moment the property was first added. Assigning a new value to an existing property keeps its position. Deleting the property and adding it again moves it to the end.
const p = { a: 1, b: 2, c: 3 };
p.a = 100; // reassign: position unchanged
console.log(Object.keys(p)); // ['a', 'b', 'c']
delete p.a;
p.a = 1; // re-created: now last
console.log(Object.keys(p)); // ['b', 'c', 'a']Spreading and Object.assign copy keys in the source's order. The new object then applies its own grouping rule. So { ...{ b: 1, 1: 'x' } } still lists '1' first.
Symbols: present but hidden
Symbol keys are ordered too, but most enumeration APIs skip them. Use Reflect.ownKeys to see the full list of own keys, or Object.getOwnPropertySymbols to see only the symbols.
const id = Symbol('id');
const obj = { [id]: 1, b: 2, 1: 'x' };
console.log(Object.keys(obj)); // ['1', 'b']
console.log(Reflect.ownKeys(obj)); // ['1', 'b', Symbol(id)]
for (const key in obj) {
console.log(key);
}
// 1
// bReflect.ownKeys also lists non-enumerable keys, which Object.keys and for...in skip.
How for...in orders inherited keys
for...in first visits the object's own enumerable keys in the order described above. Then it moves up one prototype and repeats. A key that was already visited is skipped. So is a key shadowed by a non-enumerable property lower in the chain.
const base = { inherited: 1, shared: 'base' };
const child = Object.create(base);
child.z = 1;
child[5] = 'five';
child.shared = 'child';
for (const key in child) {
console.log(key, child[key]);
}
// 5 five
// z 1
// shared child
// inherited 1The own keys come first: '5' in the numeric group, then 'z' and 'shared' in creation order. On base, 'inherited' is new and gets visited. 'shared' was already seen, so it is not repeated, and the value you read is the child's.
Object.keys never looks at the prototype, so Object.keys(child) returns ['5', 'z', 'shared'].
Which APIs follow this order
| API | Integer keys first? | Includes symbols? | Includes inherited? |
|---|---|---|---|
| `for...in` | Yes | No | Yes (enumerable) |
| `Object.keys` / `values` / `entries` | Yes | No | No |
| `Object.getOwnPropertyNames` | Yes | No | No (includes non-enumerable) |
| `Reflect.ownKeys` | Yes | Yes, last | No (includes non-enumerable) |
| `JSON.stringify` | Yes | No | No |
| `Map` iteration | No, pure insertion order | Any key type | Not applicable |
Common bugs and their fixes
The most common surprise comes from using numeric IDs as object keys and expecting them back in insertion order:
const queue = {};
queue[300] = 'third arrival';
queue[20] = 'first arrival';
queue.later = 'last';
console.log(Object.values(queue));
// ['first arrival', 'third arrival', 'last']The values come out sorted by ID, not in the order they were added. Three fixes work:
- Use a
Mapwhen insertion order matters. AMapkeeps every key, numbers included, in the order you inserted it. - Use an array when you really have a sequence.
- Sort explicitly when you need a specific order, for example
Object.keys(o).sort(), so the code states what it wants.
const ordered = new Map([['b', 1], [2, 'two'], ['a', 2], [1, 'one']]);
console.log([...ordered.keys()]);
// ['b', 2, 'a', 1]A second bug is comparing objects by their serialized form. JSON.stringify({ a: 1, b: 2 }) and JSON.stringify({ b: 2, a: 1 }) produce different strings even though the objects hold the same data. If you compare objects this way, sort the keys first.
A third bug is assuming alphabetical order. Non-integer keys are never sorted. They come out in whatever order your code created them, which may depend on the order of network responses or code paths.
Exercise
What does Object.keys print for const x = { z: 1, 10: 'a', y: 2, 2: 'b', '007': 'c' }; ?
Show answer
['2', '10', 'z', 'y', '007']. '2' and '10' are integer-like and sorted numerically. '007' has leading zeros, so it is an ordinary string key and keeps its creation position after 'z' and 'y'.
Exercise
Given const o = { a: 1, b: 2, c: 3 }; o.b = 5; delete o.a; o.a = 9; o[0] = 'zero'; what does for (const k in o) console.log(k) print?
Show answer
0, b, c, a. The integer-like key '0' comes first. Reassigning b keeps its position. Deleting and re-adding a moves it to the end of the string-key group.
Exercise
With const proto = { m: 1, n: 2 }; const obj = Object.create(proto); obj.n = 3; obj[1] = 'one'; what order does for...in visit, and what does Object.keys(obj) return?
Show answer
for...in visits 1, n, m. Own keys come first ('1', then 'n'). On the prototype, 'm' is new and gets visited, while 'n' is skipped because it was already seen. Object.keys(obj) returns ['1', 'n'].