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

By · · 1 min read
Understanding Object Keys in JavaScript (Interview Trap Question)

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

Similar Topics

#artificial intelligence (31552) #data science (24017) #ai (16747) #crypto (15110) #machine learning (14680) #featured (13553) #news & insights (13064) #the library (10944) #vc & technology (10543) #research (8564) #deep learning (7655) #news (7648) #gaming (5907) #adoption (4116) #programming (3999) #regulation (3765) #events (3308) #machine learning & data science (3114) #data visualization (2891) #opinion (2869)

Related Posts

Trending on ShareHub

Latest on ShareHub

Browse Topics

#artificial intelligence (31552) #data science (24017) #ai (16738) #generative ai (15034) #crypto (14987) #machine learning (14680) #bitcoin (14229) #featured (13550) #news & insights (13064) #crypto news (11082)

Around the Network