Map is JavaScript's true key-value data structure. Unlike objects, Map keys can be any type — objects, functions, numbers — and entries stay in insertion order. It's used in interviews for caches, frequency counters, event listeners, and anywhere you need a reliable dictionary.
Related: Data #3 — Map, Set, WeakMap, WeakSet Polyfills implements Map from scratch.
1. Why Map Over Object?
Objects have three problems as dictionaries:
Loading editor...
2. Creating a Map
Loading editor...
3. Basic Operations
Loading editor...
4. Iteration
Map is iterable and preserves insertion order:
Loading editor...
5. Object Keys
Object keys use reference equality — same reference = same key:
Loading editor...
This is why Map is perfect for storing metadata about objects without modifying the objects themselves:
Loading editor...
6. NaN and -0 as Keys
Map uses SameValueZero comparison — NaN equals NaN, and +0 equals -0:
Loading editor...
Interview use: Memoize (#10) — NaN arguments properly hit the same cache entry.
7. Map vs Object Decision Guide
| Map | Object | |
|---|---|---|
| Key types | Any value | String or Symbol only |
| Insertion order | Guaranteed | Mostly guaranteed (ES2015+) |
| Size | map.size | Object.keys(obj).length |
| Iteration | for...of, forEach | for...in + hasOwnProperty |
| Performance (frequent add/delete) | Faster | Slower |
| JSON serialization | Must convert first | Native JSON.stringify |
| Prototype collisions | None | toString, constructor, etc. |
Rule of thumb: Use Map for dictionaries with dynamic keys (especially non-string keys). Use objects for fixed-schema data and JSON serialization.
8. Common Interview Patterns
Frequency Counter
Loading editor...
Two-Sum (O(N))
Loading editor...
Event Listener Registry (#22)
Loading editor...
Data Merging by Key (#25)
Loading editor...
Quick Reference
| Method | What It Does |
|---|---|
new Map(entries?) | Create Map (optionally from [k,v] pairs) |
map.set(key, value) | Add or update entry |
map.get(key) | Get value (or undefined) |
map.has(key) | Check if key exists |
map.delete(key) | Remove entry |
map.clear() | Remove all entries |
map.size | Number of entries |
map.keys() | Iterator of keys |
map.values() | Iterator of values |
map.entries() | Iterator of [key, value] pairs |
map.forEach(fn) | Iterate with callback |
Interview Tips
- Use Map for non-string keys — "I'll use a Map so I can key by the actual object reference, not its string representation."
- Map preserves insertion order — count-by preserves the order keys are first seen.
map.get()returnsundefinedfor missing keys — distinguish from storedundefinedwithmap.has().- Use Map for event listeners —
Map<string, listener[]>avoids prototype collisions on event names.