whatstheoutput_

#95: Object.keys with numeric-looking keys

Topic: objects · Difficulty: ★★

const obj = { b: 1, 2: 'two', a: 3, 1: 'one' };
console.log(Object.keys(obj));

Output

[ '1', '2', 'b', 'a' ]

Why

Object property order isn't purely insertion order. Keys that look like array indices — strings that round-trip through a non-negative integer, like '1' and '2' — are always listed FIRST, sorted in ascending numeric order, no matter where they were written in the source. Every other key (an ordinary string like 'b' or 'a') follows afterward in the order it was inserted. That's why '1' and '2' jump to the front even though 'b' was written first in the literal.

More objects puzzles

Play today's puzzle →