whatstheoutput_

#93: obj[{}] = 1

Topic: objects · Difficulty: ★★

const obj = {};
const keyA = {};
const keyB = {};
obj[keyA] = 1;
obj[keyB] = 2;
console.log(obj[keyA]);
console.log(Object.keys(obj).length);

Output

2
1

Why

Property keys set with bracket notation are always coerced to strings first. Both keyA and keyB are plain objects, and every plain object stringifies to the same text via the default Object.prototype.toString — '[object Object]'. So obj[keyA] = 1 and obj[keyB] = 2 both actually write to the SAME string key. The second assignment overwrites the first, which is why reading obj[keyA] afterward gives 2, and why Object.keys(obj) only ever had one entry to begin with.

More objects puzzles

Play today's puzzle →