Sub topic 8
The Order Properties Come Back In
This chapter assumes you already know how to loop with Object.keys and Object.entries, how for...of works, and how to read bracket-notation property access. Here the question is narrower. When you loop over an object, which key comes first?
Many developers assume object keys come back in the order they were written. That is mostly true, but integer-like keys break the rule. Once you know the rule, the output of Object.keys and Object.entries becomes predictable.
The Rule
Object.keys, Object.values, and Object.entries all return properties in the same order. The language specification defines that order for an object's own string keys:
- Keys that look like array indexes (
"0","1","42") come first, sorted in ascending numeric order. - All other string keys come next, in the order they were first added.
Symbol keys come after both groups when you use Reflect.ownKeys. Object.keys never returns symbol keys.
const obj = { b: 'B', 2: 'two', a: 'A', 1: 'one' };
console.log(Object.keys(obj)); // ['1', '2', 'b', 'a']
console.log(Object.entries(obj)); // [['1', 'one'], ['2', 'two'], ['b', 'B'], ['a', 'A']]The keys 1 and 2 jump to the front and are sorted. The keys b and a keep their insertion order, so the result is not alphabetical. Every key comes back as a string, including the numeric ones.
What Counts as "Integer-Like"
A key counts as integer-like only if it is the canonical form of a non-negative integer. Converting it to a number and back must give the same string. A leading zero, a minus sign, or a decimal point disqualifies it.
const obj = {};
obj.z = 'letter';
obj['10'] = 'ten';
obj['01'] = 'leading zero';
obj['-1'] = 'negative';
obj['1.5'] = 'decimal';
obj[3] = 'three';
console.log(Object.keys(obj));
// ['3', '10', 'z', '01', '-1', '1.5']Only '3' and '10' are sorted to the front. The sort is numeric, so 3 comes before 10. A plain string sort would have put '10' first. The remaining keys follow in the order they were added.
Insertion Order Details
"Insertion order" means the moment a key was first created. Assigning a new value to an existing key does not move it. Deleting a key and adding it again moves it to the end of its group.
const o = { a: 1, b: 2, c: 3 };
o.a = 100; // update: position unchanged
console.log(Object.keys(o)); // ['a', 'b', 'c']
delete o.a;
o.a = 1; // re-created: goes to the end
console.log(Object.keys(o)); // ['b', 'c', 'a']Object spread and Object.assign copy properties in source order, so this rule also controls the key order of the copies they produce.
When You Need a Different Order
If you need a specific order, sort the keys or entries yourself. Do not rely on how the object was built.
const scores = { carol: 85, alice: 90, bob: 72 };
const byName = Object.keys(scores).sort();
console.log(byName); // ['alice', 'bob', 'carol']
const byScore = Object.entries(scores).sort(([, a], [, b]) => b - a);
console.log(byScore); // [['alice', 90], ['carol', 85], ['bob', 72]]If you need numeric keys to stay in insertion order, use a Map. A Map keeps strict insertion order for every key type, and it does not convert numeric keys to strings.
const m = new Map([[2, 'two'], [1, 'one']]);
console.log([...m.keys()]); // [2, 1]| Need | Use |
|---|---|
| Rely on the default object order | `Object.keys` / `Object.entries` as is |
| Alphabetical or value-based order | `.sort()` on the keys or entries array |
| Insertion order with numeric keys | `Map` |
Exercise
What does this log? const inv = { 20: 'x', beta: 'y', 5: 'z', '007': 'w', alpha: 'v' }; inv.beta = 'updated'; delete inv.alpha; inv.alpha = 'back'; console.log(Object.keys(inv));
Show answer
['5', '20', 'beta', '007', 'alpha']. The integer-like keys 5 and 20 come first in numeric order. '007' has leading zeros, so it is an ordinary string key and keeps its insertion position after beta. Updating beta does not move it. Deleting alpha and adding it again moves it to the end.
Exercise
You store products in an object keyed by numeric product ID, adding them in the order a customer added them to the cart. Why does the cart display in the wrong order, and what are two fixes?
Show answer
Integer-like keys are always returned in ascending numeric order, so the IDs come back sorted instead of in the order they were added. Fix it by storing the cart in a Map, which keeps insertion order for every key, or by using an array of items, which has an explicit order.