JavaScript Map vs Object: Key Differences and Use Cases

Day 40/50 – JavaScript Interview Question? Question: What is the Map object and how does it differ from a plain Object? Simple Answer: A Map is a key-value collection where keys can be any type (objects, functions, primitives). Unlike plain objects, Maps maintain insertion order, have a size property, are iterable by default, and don't have prototype chain issues. 🧠 Why it matters in real projects: Maps are superior for frequently adding/removing entries, using non-string keys (like objects or DOM elements), maintaining order, and avoiding prototype pollution. They're essential for caching, memoization, and when you need dictionary-like behavior with better performance. 💡 One common mistake: Using objects as dictionaries when Map would be more appropriate, especially when keys might collide with prototype properties like toString or constructor. Also, forgetting that object keys are always converted to strings. 📌 Bonus: // Creating Maps const map = new Map(); map.set('name', 'Alice'); map.set(42, 'number key'); map.set(true, 'boolean key'); // Objects as keys (impossible with plain objects!) const objKey = { id: 1 }; map.set(objKey, 'object value'); // Basic operations map.get('name'); // 'Alice' map.has(42); // true map.delete(true); // Remove entry map.size; // 3 (not length) map.clear(); // Remove all // Key differences from Objects: // 1. Any type as key const func = () => {}; map.set(func, 'function key'); // ✓ Works! const obj = { [func]: 'test' }; // ✗ Converts to string // 2. Size property (O(1)) map.size; // Instant Object.keys(obj).length; // O(n) - slower // 3. Iteration order guaranteed const map2 = new Map(); map2.set('z', 1); map2.set('a', 2); map2.set('m', 3); for (let [key, value] of map2) { console.log(key); // 'z', 'a', 'm' (insertion order) } // 4. No prototype pollution const obj2 = {}; obj2.toString = 'hacked'; // Problem! const map3 = new Map(); map3.set('toString', 'safe'); // No issues // Practical use cases: // Caching with object keys const cache = new Map(); function expensiveOp(obj) { if (cache.has(obj)) { return cache.get(obj); } const result = /* expensive calculation */; cache.set(obj, result); return result; } // Counting occurrences const count = new Map(); for (let item of items) { count.set(item, (count.get(item) || 0) + 1); } // Converting between Object and Map const obj3 = { a: 1, b: 2 }; const map4 = new Map(Object.entries(obj3)); const obj4 = Object.fromEntries(map4); // When to use Map vs Object: // Use Map: frequent add/delete, non-string keys, need size // Use Object: static structure, JSON serialization, prototype methods #JavaScript #WebDevelopment #Frontend #LearnInPublic #InterviewQuestions #Programming #TechInterviews #Map #DataStructures #InterviewPrep #ES6

To view or add a comment, sign in

Explore content categories