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

Why do object keys 1 and "1" overwrite each other?

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

JavaScript
const obj = {};
obj[1] = "a";
obj["1"] = "b";
console.log(obj[1]);
Show answer and explanation

The answer is "b".

Plain object keys are converted to strings. obj[1] and obj["1"] are the same property, so the second assignment overwrites the first. A Map keeps them separate.

Take the full quiz Next question →

More Objects questions

  1. What happens when you use an object as an object key?
  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