DEV Community

Ship Stack
Ship Stack

Posted on Originally published at youtube.com

Does Object.keys keep your insert order in JavaScript?

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}
Enter fullscreen mode Exit fullscreen mode

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:

  1. Integer indices, ascending.
  2. String keys, in insertion order.
  3. 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' ]
Enter fullscreen mode Exit fullscreen mode

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...in and 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. A Map keeps insertion order for every key type: the same four keys inserted as b, 2, a, 1 came back as b, 2, a, 1 in the same run.
const m = new Map([["b",1],[2,2],["a",3],[1,4]]);
console.log([...m.keys()]); // [ 'b', 2, 'a', 1 ]
Enter fullscreen mode Exit fullscreen mode

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

Top comments (0)