Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 1

Integer keys and property order in JavaScript objects

147 the order object keys come out in

hard

Insert keys into an object in a deliberately jumbled order: plain names, small integers, a negative number, a decimal, a zero-padded number, the largest possible array index and the one just past it, and a symbol. Then report the order given by Object.keys, Reflect.ownKeys, JSON.stringify, spread and for...in. Show what delete and re-insert does to a string key against an integer key, and what a Map does with the same sequence.

Stuck? Three hints, smallest first
  1. 1. There are three groups, always in this order: integer-like keys ascending by value, then string keys in insertion order, then symbols in insertion order.
  2. 2. A key counts as integer-like only if String(Number(key)) === key and it is below 2**32 - 1, so '-1', '1.5' and '01' are ordinary strings.
  3. 3. for...in adds inherited enumerable string keys after the own ones, and spread is the only one of these that carries symbols across.

The answer

const tag = Symbol('tag');
const ledger = {};
ledger.zebra = 1;
ledger[2] = 'two';
ledger.apple = 2;
ledger[1] = 'one';
ledger['-1'] = 'minus one';
ledger['1.5'] = 'one and a half';
ledger['01'] = 'zero one';
ledger[tag] = 'a symbol value';
ledger[0] = 'zero';
ledger['4294967294'] = 'the largest array index';
ledger['4294967295'] = 'one past it';

const keys = Object.keys(ledger);
const ownKeys = Reflect.ownKeys(ledger).map(String);
const json = JSON.stringify(ledger);
const keyOrderInJson = (json.match(/"[^"]*":/g) || []).map((s) => s.slice(1, -2));
const spread = { ...ledger };
const spreadKeys = Object.keys(spread);
const symbolsCarried = [Object.getOwnPropertySymbols(ledger).length, Object.getOwnPropertySymbols(spread).length];

const literal = { b: 1, 2: 'x', a: 2, 1: 'y' };
const literalKeys = Object.keys(literal);

const parent = { inherited: true };
const child = Object.create(parent);
child.own2 = 1;
child[5] = 1;
child.own1 = 1;
const forIn = [];
for (const key in child) forIn.push(key);

const reinsert = { a: 1, b: 2, c: 3, 1: 'one', 2: 'two' };
delete reinsert.a;
reinsert.a = 9;
delete reinsert[1];
reinsert[1] = 'back';
const reinsertKeys = Object.keys(reinsert);

const asMap = new Map();
asMap.set('zebra', 1).set(2, 'two').set('apple', 2).set(1, 'one');
const mapKeys = [...asMap.keys()];
const mapKeyTypes = mapKeys.map((k) => typeof k);

const expected = ['0', '1', '2', '4294967294', 'zebra', 'apple', '-1', '1.5', '01', '4294967295'];

console.log('Object.keys   :', keys);
console.log('Reflect.ownKeys:', ownKeys);
console.log('in the JSON   :', keyOrderInJson);
console.log('spread        :', spreadKeys, '| symbols:', symbolsCarried);
console.log('literal       :', literalKeys, '| for...in:', forIn);
console.log('delete/re-add :', reinsertKeys);
console.log('a Map instead :', mapKeys, mapKeyTypes);

Output


      
9 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 9 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

9 checks

test('integer-like keys first and ascending, then the string keys in insertion order', keys, expected);
test('a negative, a decimal, a padded number and 2**32-1 are all ordinary strings', [keys.indexOf('-1') > keys.indexOf('zebra'), keys.indexOf('4294967295'), keys.length], [true, 9, 10]);
test('an object literal is normalised exactly the same way', literalKeys, ['1', '2', 'b', 'a']);
test('JSON.stringify follows the same order and drops the symbol', [keyOrderInJson, json.includes('symbol')], [expected, false]);
test('spread keeps the order and is the one that copies symbols across', [spreadKeys, symbolsCarried], [expected, [1, 1]]);
test('Reflect.ownKeys appends symbols after every string key', [ownKeys.length, ownKeys[10]], [11, 'Symbol(tag)']);
test('for...in normalises own keys the same way, then walks up the prototype chain', forIn, ['5', 'own2', 'own1', 'inherited']);
test('delete and re-add sends a string key to the back, but an integer key returns to its slot', reinsertKeys, ['1', '2', 'b', 'c', 'a']);
test('a Map keeps genuine insertion order and does not stringify its keys', [mapKeys, mapKeyTypes], [['zebra', 2, 'apple', 1], ['string', 'number', 'string', 'number']]);

Key order was unspecified until ES2015 and is now pinned down exactly, which is worse news than it sounds: the specified order is not insertion order. Own property enumeration builds three groups. Integer-index keys first, sorted numerically ascending. Then all other string keys, in the order they were created. Then symbols, in creation order. Object.keys, Object.values, Object.entries, JSON.stringify, spread, Object.assign and for...in all follow it, so there is no method that will hand back the order you typed.

The definition of integer-index is narrow and worth knowing precisely: the key must be the canonical decimal form of a non-negative integer below 2**32 - 1. So '-1', '1.5' and '01' are ordinary strings, and so is '4294967295' — one past the largest array index — while '4294967294' jumps to the front and sorts numerically. That is why an object keyed by numeric ids silently reorders itself, and why { 10: a, 9: b } comes out 9 then 10.

delete makes it concrete. Removing and re-adding a string key moves it to the end of its group, so an innocuous update reorders your JSON, but an integer key drops back into its numeric slot as if nothing happened. When order carries meaning, do not store it in object keys: use a Map, which preserves true insertion order and keeps a number a number rather than coercing it to a string. If you must use an object, sort explicitly at the point of use and stop depending on the shape of the literal.

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.