Sub topic 5
The Order of Property Keys
This chapter assumes you know how for...in walks an object's enumerable keys and how inherited properties show up in that walk. The question here is the order in which the keys arrive. The order is not random. The specification defines it, and for...in, Object.keys, Object.values and Object.entries all follow the same rules.
The Rule for Own Properties
An object's own string keys come out in two groups:
- Integer-like keys in ascending numeric order. An integer-like key is a string such as
'0'or'42'that is the canonical form of a non-negative integer (array indices up to 2³² − 2). - All other string keys in the order they were created.
Symbol keys come after both groups, but for...in and Object.keys skip them. Only Reflect.ownKeys and Object.getOwnPropertySymbols show them.
const o = { b: 1, 2: 'two', a: 2, 1: 'one' };
console.log(Object.keys(o));
// ['1', '2', 'b', 'a']The keys 1 and 2 move to the front and are sorted. The keys b and a stay in the order they were written.
Common Surprises
Only canonical non-negative integers are sorted. Negative numbers, decimals and strings with leading zeros count as ordinary string keys and keep their creation order:
const o = { z: 1, '-1': 'neg', 10: 'ten', '01': 'lead', 1.5: 'x', 3: 'three' };
console.log(Object.keys(o));
// ['3', '10', 'z', '-1', '01', '1.5']Deleting a key and adding it back moves it to the end of the string group, because it becomes a newly created property:
const p = { a: 1, b: 2 };
delete p.a;
p.a = 3;
console.log(Object.keys(p)); // ['b', 'a']Assigning a new value to an existing key does not change its position.
Order with Inherited Keys
for...in lists the object's own keys first, in the order described above. It then moves up the prototype chain and lists each prototype's keys the same way. A key that an own property already shadows is not listed a second time.
const base = { y: 'base', x: 'base' };
const obj = Object.create(base);
obj.b = 1;
obj.x = 'own';
for (const key in obj) {
console.log(key);
}
// b
// x
// yExercise
What does Object.keys return for { c: 1, 100: 'a', '007': 'b', 5: 'c', a: 2 }?
Show answer
['5', '100', 'c', '007', 'a']. The integer-like keys 5 and 100 come first in ascending order. '007' has leading zeros, so it is an ordinary string key and keeps its creation position among c and a.
Exercise
You run const m = { a: 1, b: 2, c: 3 }; delete m.b; m.b = 4; m.a = 5; What does Object.keys(m) return?
Show answer
['a', 'c', 'b']. Re-adding b after deleting it moves it to the end. Assigning a new value to a, which already exists, leaves its position unchanged.