Explorer
JavaScript

Map and Set

JavaScript Theory & Concepts

Map and Set in JavaScript

High-performance key-value maps, unique sets, and O(1) collection operations.

📖 The Story & Real-World Analogy

The VIP Club Door and the Master Locker Matrix

"• **Set**: A VIP nightclub door with a biometric scanner. When a guest arrives, the scanner checks the roster. If "Charlie" tries to enter 10 times, the bouncer only admits one Charlie. Duplicate entries are physically impossible, and checking membership is instantaneous (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.

⚙️ How It Works Under The Hood (Step-by-Step)
1

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.

2

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.

3

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

4

Modern Set Methods (ES2024)

Native methods: `setA.intersection(setB)`, `setA.union(setB)`, `setA.difference(setB)`, and `setA.isSubsetOf(setB)`.

💻 Interactive Code Walkthrough

Deduplicating arrays with Set and keying a Map by object references:

JAVASCRIPT
// 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}`);
}
Console Output:
CODE
Deduplicated: [ 1, 2, 3, 4, 5 ]
User A token: token_abc_123
Total active sessions: 2
Alice has role admin
Bob has role member
⚠️ Common Pitfalls & Interview Traps
Trap
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.

⚡ 30-Second Quick Revision Cheat Sheet (TL;DR)
  • ✓ `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.

Finished this lesson?

Mark this chapter complete to update your learning streak and unlock the next lesson.