Understanding Object Keys in JavaScript (Interview Trap Question)
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 outpu...

Source: DEV Community
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: C