Sub topic 8
The Order Properties Come Back In
When you loop over an object with Object.keys, Object.values, or Object.entries, the properties arrive in a fixed, predictable order. That order is not always the order you typed them in. Code that renders a list, builds a report, or compares two objects often depends on this order without anyone noticing, so knowing the rules saves debugging time.
This chapter assumes you know object literals, bracket notation, arrays, for...of, and Object.keys/Object.entries from the earlier chapters. You should also be comfortable with Array.prototype.sort and a comparator function.
The rule in one sentence
An object's own string keys come back in two groups. First come the keys that look like array indexes, in ascending numeric order. Then come all other string keys, in the order they were created.
const obj = { b: 'B', 2: 'two', a: 'A', 1: 'one' };
console.log(Object.keys(obj)); // ['1', '2', 'b', 'a']
console.log(Object.values(obj)); // ['one', 'two', 'B', 'A']
console.log(Object.entries(obj));
// [['1', 'one'], ['2', 'two'], ['b', 'B'], ['a', 'A']]Note three things in that output:
1and2moved to the front even though they were written second and fourth.bandakept their insertion order. They were not sorted alphabetically.- The numeric keys come back as the strings
'1'and'2'. Property keys are always strings (or symbols), so the number you typed was converted when the property was created.
All three methods use the same internal ordering, so Object.keys(obj)[i] and Object.values(obj)[i] always refer to the same property.
What counts as "integer-like"
The specification calls the first group array indexes. A key is an array index if it is the canonical string form of a whole number from 0 up to 4294967294 (2³² − 2). "Canonical" means converting the string to a number and back gives the same string. That excludes leading zeros, signs, decimals, and whitespace.
const tricky = { z: 'f', '10': 'a', '9': 'b', '01': 'c', '-1': 'd', '1.5': 'e' };
console.log(Object.keys(tricky));
// ['9', '10', 'z', '01', '-1', '1.5']Walk through it:
| Key | Array index? | Why |
|---|---|---|
| `'9'` | Yes | `String(Number('9')) === '9'` |
| `'10'` | Yes | Whole number in range |
| `'z'` | No | Not numeric |
| `'01'` | No | `String(Number('01'))` is `'1'`, not `'01'` |
| `'-1'` | No | Negative numbers are not array indexes |
| `'1.5'` | No | Not a whole number |
The numeric group is sorted numerically, so '9' comes before '10'. A plain string sort would put '10' first. The non-index keys 'z', '01', '-1', and '1.5' keep their creation order, even though three of them look like numbers.
Keys at or above 4294967295 are also treated as ordinary string keys and stay in insertion order. You will rarely hit this, but it can matter if you key objects by large numeric IDs or timestamps.
Creation order, precisely
"Creation order" means the moment the property was first added to the object. Two operations interact with it in ways people often get wrong.
Assigning a new value to an existing property does not move it. Deleting a property and adding it again does move it to the end, because it is a new property.
const o = { a: 1, b: 2, c: 3 };
o.a = 100; // update in place
console.log(Object.keys(o)); // ['a', 'b', 'c']
delete o.a;
o.a = 1; // re-created, so it goes last
console.log(Object.keys(o)); // ['b', 'c', 'a']For object literals, creation order is the order the properties appear in the source. A duplicate key in a literal keeps the position of its first appearance and the value of its last:
const dup = { x: 1, y: 2, x: 3 };
console.log(Object.entries(dup)); // [['x', 3], ['y', 2]]Spread and Object.assign copy properties in the source's key order. When the target already has a key, the copy updates it in place:
const defaults = { theme: 'light', size: 12, lang: 'en' };
const user = { lang: 'fr', theme: 'dark' };
const merged = { ...defaults, ...user };
console.log(Object.keys(merged)); // ['theme', 'size', 'lang']
console.log(merged); // { theme: 'dark', size: 12, lang: 'fr' }The keys of merged follow defaults, because defaults created them first. user only overwrote values.
Same order everywhere
The same ordering rule is shared by most of the language's own-property operations:
Object.keys,Object.values,Object.entriesObject.assignand object spreadJSON.stringify- The own-property part of
for...in Object.getOwnPropertyNamesandReflect.ownKeys
console.log(JSON.stringify({ b: 1, 2: 2, a: 3 })); // {"2":2,"b":1,"a":3}Reflect.ownKeys adds a third group: symbol keys, in creation order, after all string keys. The later chapter on hidden properties covers why Object.keys leaves those out.
const s = Symbol('s');
const mixed = { [s]: 'sym', b: 1, 0: 'zero' };
console.log(Reflect.ownKeys(mixed)); // ['0', 'b', Symbol(s)]The common bug: objects keyed by numeric IDs
The rule hurts most when you build an object from data that already has a meaningful order and the keys happen to be numeric.
// API returns products ranked by popularity
const ranked = [
{ id: 102, name: 'Lamp' },
{ id: 7, name: 'Desk' },
{ id: 55, name: 'Chair' },
];
const byId = {};
for (const p of ranked) {
byId[p.id] = p.name;
}
console.log(Object.values(byId)); // ['Desk', 'Chair', 'Lamp']The popularity ranking is gone. The object sorted its keys by ID because every key was an array index. Nothing threw an error, and the output still looks plausible, which is why this bug ships.
You have three fixes, depending on what you need.
Keep the array for order, use the object for lookup
If you need both fast lookup and the original order, store them separately. Loop over the array when order matters and use the object only for lookups.
const order = ranked.map((p) => p.id); // [102, 7, 55]
const names = Object.fromEntries(ranked.map((p) => [p.id, p.name]));
for (const id of order) {
console.log(id, names[id]);
}
// 102 Lamp
// 7 Desk
// 55 ChairUse a Map
A Map keeps every key in insertion order, numeric or not, and it does not convert keys to strings.
const byIdMap = new Map(ranked.map((p) => [p.id, p.name]));
console.log([...byIdMap.keys()]); // [102, 7, 55]
console.log([...byIdMap.values()]); // ['Lamp', 'Desk', 'Chair']
for (const [id, name] of byIdMap) {
console.log(typeof id, id, name);
}
// number 102 Lamp
// number 7 Desk
// number 55 ChairThe trade-off is that a Map does not serialize with JSON.stringify directly (you get {}), and it does not work with dot or bracket access. Convert with Object.fromEntries(map) or [...map] at the boundary.
Make the keys non-numeric
Prefixing the key, such as 'id_102', moves it into the creation-order group. This works but spreads a formatting rule through your code. Prefer one of the other two fixes.
Choosing an order on purpose
The built-in order is fixed, but you rarely want "array indexes first, then insertion order" for display anyway. When order matters to the user, sort explicitly. Object.entries returns a fresh array, so sorting it does not touch the object.
const stock = { pear: 4, apple: 12, fig: 7, banana: 12 };
// Alphabetical by key
const byName = Object.entries(stock).sort(([a], [b]) => a.localeCompare(b));
console.log(byName);
// [['apple', 12], ['banana', 12], ['fig', 7], ['pear', 4]]
// Highest value first; ties keep their original relative order
const byCount = Object.entries(stock).sort(([, a], [, b]) => b - a);
console.log(byCount);
// [['apple', 12], ['banana', 12], ['fig', 7], ['pear', 4]]Array.prototype.sort is stable since ES2019, so apple stays ahead of banana in the second sort because it came first in Object.entries(stock).
Be careful about turning a sorted array back into an object with Object.fromEntries. String keys keep the sorted order, but array-index keys are re-sorted numerically, which undoes a sort by value:
const votes = { 3: 10, 1: 50, 2: 30 };
const sorted = Object.entries(votes).sort(([, a], [, b]) => b - a);
console.log(sorted); // [['1', 50], ['2', 30], ['3', 10]]... by value
const back = Object.fromEntries(Object.entries(votes).sort(([, a], [, b]) => a - b));
console.log(Object.keys(back)); // ['1', '2', '3'], not ['3', '2', '1']If the order must survive, keep the sorted array or put it in a Map.
Should code depend on this order?
The order is specified, so depending on it is not undefined behavior. A reasonable guideline:
| Situation | Rely on built-in order? |
|---|---|
| Config objects or literals you wrote, with non-numeric keys | Yes, insertion order is stable and readable |
| Snapshot tests or `JSON.stringify` comparisons of objects you built | Usually, but build them in the same order |
| Keys from user input or external IDs | No, they may be numeric |
| Anything shown to users in a specific order | No, sort explicitly or use an array |
| Comparing two objects for equality | No, compare by key lookup instead of by position |
Exercise
What does this log, and why? const o = { b: 1, '2': 2, '007': 3, a: 4, 1: 5 }; delete o.b; o.b = 6; console.log(Object.keys(o));
Show answer
['1', '2', '007', 'a', 'b']. The array-index keys '1' and '2' come first in ascending numeric order. '007' is not canonical (String(Number('007')) is '7'), so it is an ordinary string key and keeps its creation position. 'b' was deleted and re-created, so it moves after 'a' to the end of the string group.
Exercise
A leaderboard object is built as scores[userId] = points, where userId values are numbers such as 881, 12, and 430, inserted from highest score to lowest. Object.entries(scores) then shows users in ID order. Give two fixes that preserve the ranking.
Show answer
Store the entries in a Map (new Map(), then map.set(userId, points)), which keeps insertion order for numeric keys. Or keep an array of [userId, points] pairs, or an array of IDs alongside the object, and loop over the array. Alternatively, sort Object.entries(scores) by points at display time with .sort(([, a], [, b]) => b - a) and keep the result as an array, not an object.
Exercise
Given const m = { ...{ x: 1, y: 2 }, ...{ z: 3, x: 9 } }, what are Object.keys(m) and m.x?
Show answer
Object.keys(m) is ['x', 'y', 'z'] and m.x is 9. The first spread creates x and y. The second spread creates z at the end and updates x in place, so x keeps its original first position.