Map and Set
Map and Set in JavaScript
High-performance key-value maps, unique sets, and O(1) collection operations.
The VIP Club Door and the Master Locker Matrix
O(1))!
• **Map**: A high-tech locker system. Unlike standard wooden lockers (plain objects) that only accept paper labels (strings or symbols), this matrix accepts ANY physical item as a key: you can use a company badge, a coffee mug, or another locker as the key to open a compartment."
`Map` and `Set` were introduced in ES6 to provide fast, hash-based keyed collections and unique sets with predictable iteration order and native size inspection.
Map vs Plain Objects
Map keys can be of any type (including objects and functions). Map preserves insertion order, provides a direct `.size` property, and does not inherit prototype collisions.
Set vs Arrays
Set stores only unique values. Checking presence via `set.has(val)` takes O(1) constant time, whereas `array.includes(val)` takes O(N) linear time.
Map & Set Operations
`map.set(k, v)`, `map.get(k)`, `map.has(k)`, `map.delete(k)`, `map.clear()`. `set.add(v)`, `set.has(v)`, `set.delete(v)`. Both have `.size`.
Modern Set Methods (ES2024)
Native methods: `setA.intersection(setB)`, `setA.union(setB)`, `setA.difference(setB)`, and `setA.isSubsetOf(setB)`.
Deduplicating arrays with Set and keying a Map by object references:
// 1. O(N) Array Deduplication using Set
const rawNumbers = [1, 2, 2, 3, 4, 4, 5];
const uniqueNumbers = [...new Set(rawNumbers)];
console.log("Deduplicated:", uniqueNumbers);
// 2. Map with Object References as Keys
const sessionCache = new Map();
const userA = { id: 1, name: "Alice" };
const userB = { id: 2, name: "Bob" };
sessionCache.set(userA, { token: "token_abc_123", role: "admin" });
sessionCache.set(userB, { token: "token_xyz_789", role: "member" });
console.log("User A token:", sessionCache.get(userA).token);
console.log("Total active sessions:", sessionCache.size);
// Iterating a Map in insertion order
for (const [user, session] of sessionCache.entries()) {
console.log(`${user.name} has role ${session.role}`);
}
Deduplicated: [ 1, 2, 3, 4, 5 ]
User A token: token_abc_123
Total active sessions: 2
Alice has role admin
Bob has role member
Keying Map with Object Literals without Reference
The Risk: `map.set({ a: 1 }, "data"); console.log(map.get({ a: 1 }));` returns `undefined` because the two object literals occupy different heap memory addresses.
The Fix: Retain the variable reference to the object used as the key.
-
✓
`Set`: Unique values only,
O(1)lookups via `.has()`. - ✓ One-line array deduplication: `[...new Set(arr)]`.
- ✓ `Map`: Keys can be ANY type (objects, functions, primitives).
- ✓ Both maintain strict insertion order during iteration.
- ✓ Check collection size directly with `.size` property.