Assign the keys b, 2, a, 1 to a plain object and Object.keys comes back as 1, 2, b, a. That is not a bug and it is not random: the spec splits keys into two groups and sorts one of them.
The test
const o = {}; o.b = 1; o[2] = 2; o.a = 3; o[1] = 4; console.log(Object.keys(o)); // [ '1', '2', 'b', 'a' ] console.log(JSON.stringify(o)); // {"1":4,"2":2,"b":1,"a":3} The integer-like keys "1" and "2" came first, in ascending numeric order. The string keys b and a followed in the order they were inserted. The integer keys were inserted 2 then 1, and the output is 1 then 2.
The rule
Own property keys of an ordinary object are enumerated in three groups:
- Integer indices, ascending.
- String keys, in insertion order.
- Symbols, in insertion order.
An "integer index" is a canonical numeric string that is a non-negative integer below 2^32 - 1. "01", "1.5" and "-1" are not integer indices, so they stay in the string group:
console.log(Object.keys({"01":"a","1.5":"b","-1":"c",b:1,a:2,"3":"d"})); // [ '3', '01', '1.5', '-1', 'b', 'a' ] Only the "3" was hoisted to the front. Everything else kept insertion order.
When it bites
- You build an object keyed by numeric ids, serialise it, and the JSON key order is not the order you built. Snapshot tests and anything that diffs JSON strings start failing for no visible reason.
-
Object.entries,for...inand object spread all follow the same order, so a loop over an object is not insertion order once integer-like keys are in play. - If order is part of the meaning, use a
Map. AMapkeeps insertion order for every key type: the same four keys inserted asb,2,a,1came back asb,2,a,1in the same run.
const m = new Map([["b",1],[2,2],["a",3],[1,4]]); console.log([...m.keys()]); // [ 'b', 2, 'a', 1 ] Plain objects are fine for unordered data. The moment you rely on the order, either keep every key a non-integer string or switch to a Map.
How this was tested
Real run in Node.js 22. The narration in the video is an AI-generated voice; every output above came from the terminal. Short video with the same run: https://youtube.com/shorts/ilYPA3GZGmI