JavaScript Challenge: Unexpected Output with Objects as Keys

🚀 Day 2 – Level 2 of my 4 Days JavaScript Challenge! 💡 Today's question: Why is the output of this code unexpected? 🤔 const obj = {}; const a = { id: 1 }; const b = { id: 2 }; obj[a] = "A"; obj[b] = "B"; console.log(obj[a]); // ❓ 🧠 Expected Output: "A" 😅 Actual Output: "B" 👉 Reason: When you use objects as keys in a plain JavaScript object {}, they are automatically converted to strings — specifically "[object Object]". So in the above code: obj[a] ➜ obj["[object Object]"] = "A" obj[b] ➜ obj["[object Object]"] = "B" Both keys collide because they share the same string representation, and the last one ("B") overwrites the first one. ✅ Correct Approach – Use Map instead! const map = new Map(); const a = { id: 1 }; const b = { id: 2 }; map.set(a, "A"); map.set(b, "B"); console.log(map.get(a)); // "A" console.log(map.get(b)); // "B" 🧩 Key Takeaway: Use Map when you need object references as keys — it preserves their identity and avoids overwriting issues. 🔥 Coming up tomorrow – Day 3: One of the most confusing yet important JavaScript interview concepts you must master! #JavaScript #FrontendDevelopment #WebDevelopment #CodingChallenge #CleanCode #InterviewPreparation #TechJourney #Objects #Map #JSInterview

Nice example. It’s a simple way to show why map can be so useful compared to plain objects

Like
Reply

To view or add a comment, sign in

Explore content categories