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...
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