Your product could be here, in front of thousands of JavaScript developers. Sponsor this spot →
JavaScript Quiz

What happens when you use an object as an object key?

Do you know what will be the output of this code?

JavaScript
const a = {};
const b = { key: "b" };
const c = { key: "c" };

a[b] = 123;
a[c] = 456;
console.log(a[b]);
Show answer and explanation

The answer is 456.

Both b and c become the string "[object Object]" when used as keys. The second assignment overwrites the first. Use a Map for object keys.

Take the full quiz Next question →

More Type Coercion questions

  1. Why do object keys 1 and "1" overwrite each other?
  2. Why is {} === {} false in JavaScript?
  3. Are JavaScript objects copied by reference?
  4. Does the spread operator make a deep copy?
  5. Is Object.freeze deep or shallow?

Related topics