I was recently asked an interesting JavaScript question in an interview:
let obj = {};
let a = { a: 10 };
let b = { b: 20 };
obj[a] = 10;
obj[b] = 20;
console.log(obj[a]);
π€ What will be the output?
π Output: 20
π Why does this happen?
In JavaScript, object keys can only be of type string or symbol.
When you use an object as a key:
obj[a] = 10;
JavaScript internally converts the key to a string using .toString():
a.toString() // "[object Object]"
b.toString() // "[object Object]"
So effectively, your code becomes:
obj["[object Object]"] = 10;
obj["[object Object]"] = 20;
π The second assignment overwrites the first one.
So:
console.log(obj[a]); // 20
π Follow-up Question 1: How to fix this issue?
β
Option 1: Use Map (Recommended)
If you want to use objects as keys, use Map:
const map = new Map();
map.set(a, 10);
map.set(b, 20);
console.log(map.get(a)); // 10
console.log(map.get(b)); // 20
π Map preserves reference identity, so a and b are treated as different keys.
β οΈ Option 2: Convert keys to unique strings (Not ideal)
let obj = {};
let a = JSON.stringify({ a: 10 });
let b = JSON.stringify({ b: 20 });
obj[a] = 10;
obj[b] = 20;
console.log(obj[a]); // 10
π This works, but:
- Itβs fragile
- Depends on consistent serialization
- Not suitable for complex objects
β οΈ Option 3: Use Symbol
let obj = {};
let a = Symbol("a");
let b = Symbol("b");
obj[a] = 10;
obj[b] = 20;
console.log(obj[a]); // 10
π Symbols are always unique:
Symbol("a") === Symbol("a") // false
π Follow-up Question 2: What is the data type of object keys?
In JavaScript:
-
Object keys are always:
stringsymbol
Even if you use:
obj[1] = "value";
obj[true] = "value";
obj[null] = "value";
They are converted to strings:
obj["1"]
obj["true"]
obj["null"]
π When should you use Map instead of Object?
Use Map when:
- Keys are objects or functions
- You need preserved insertion order
- You want better performance for frequent add/remove
- You need strict key equality (no coercion)
β‘ Bonus: Key Differences (Object vs Map)
| Feature | Object | Map |
|---|---|---|
| Key Types | String, Symbol | Any type |
| Key Conversion | Yes (to string) | No |
| Order Guarantee | Not reliable | Preserved |
| Performance | Good | Better for dynamic use |
| Iteration | Limited | Built-in methods |
π§ Final Takeaway
- Objects coerce keys to strings, which can cause collisions.
- This is why both
aandbbecame"[object Object]". - To safely use non-string keys, always prefer
Map.
This is a classic interview question designed to test:
- JavaScript coercion rules
- Object internals
- Practical knowledge of
Map
Top comments (0)