← JS Mastery | Module 4: Objects & Arrays Map, Set, WeakMap & WeakSet
Module 4

Map, Set, WeakMap & WeakSet

⏱ 20 min read ● Intermediate 🆓 Free

Set — Unique Value Collections

A Set is a collection of unique values. It automatically removes duplicates and has efficient has/add/delete operations.

// Creating a Set
const colors = new Set(["red", "green", "blue", "red"]);
console.log(colors); // Set(3) {"red","green","blue"} — dup removed!
console.log(colors.size); // 3

// Adding/checking/deleting
colors.add("yellow");     // Set now has 4 items
colors.has("red");        // true
colors.has("purple");     // false
colors.delete("green");   // removes it, returns true/false
colors.clear();           // removes everything

// Iterating a Set
const nums = new Set([1, 2, 3, 4, 5]);
for (const n of nums) {
  console.log(n);  // 1, 2, 3, 4, 5
}
console.log([...nums]);  // [1,2,3,4,5] — spread to array

// Remove duplicates from array:
const withDups = [1,2,2,3,3,3,4];
const unique = [...new Set(withDups)]; // [1,2,3,4]

// Set operations (no built-in, but easy to implement):
const a = new Set([1,2,3,4]);
const b = new Set([3,4,5,6]);
const union = new Set([...a, ...b]);          // {1,2,3,4,5,6}
const intersection = new Set([...a].filter(x => b.has(x))); // {3,4}
const difference = new Set([...a].filter(x => !b.has(x)));  // {1,2}

Map — Key-Value with Any Key Type

A Map is like an object but with superpowers: any value can be a key (not just strings/symbols), and it maintains insertion order.

// Creating a Map
const userRoles = new Map();
userRoles.set("alice@example.com", "admin");
userRoles.set("bob@example.com", "user");

// Or initialize with entries:
const scores = new Map([
  ["Alice", 95],
  ["Bob", 87],
  ["Charlie", 92]
]);

// Accessing data
scores.get("Alice");      // 95
scores.has("Bob");        // true
scores.size;              // 3
scores.delete("Bob");     // removes Bob

// ANY type can be a key (unlike object keys which are strings/symbols):
const map = new Map();
const keyObj = { id: 1 };
const keyFn = function() {};
map.set(keyObj, "object key");
map.set(keyFn, "function key");
map.set(42, "number key");
map.get(keyObj);  // "object key"

// Iterating a Map
for (const [key, value] of scores) {
  console.log(`${key}: ${value}`);
}
[...scores.keys()];    // ["Alice","Charlie"]
[...scores.values()];  // [95,92]
[...scores.entries()]; // [["Alice",95],["Charlie",92]]

// Convert to/from object:
const obj = Object.fromEntries(scores);
const backToMap = new Map(Object.entries(obj));

WeakMap & WeakSet

// WeakMap — keys must be objects, garbage collected when no refs
// Use case: associate private data with objects without memory leaks
const privateData = new WeakMap();

class User {
  constructor(name, password) {
    privateData.set(this, { password });
    this.name = name;
  }
  checkPassword(pwd) {
    return privateData.get(this).password === pwd;
  }
}

const user = new User("Alice", "secret");
user.checkPassword("secret"); // true
// user.password doesn't exist on the public object!
// When user is garbage collected, WeakMap cleans up automatically

// WeakSet — stores objects weakly (no size, no iteration)
const visited = new WeakSet();
function processNode(node) {
  if (visited.has(node)) return;  // already processed
  visited.add(node);
  // process...
}
// When nodes are removed, WeakSet cleans up — no memory leak

When to Use What

Use CaseUse
Unique values from arraySet
Check if item exists quicklySet
String keys, simple dataObject
Non-string keysMap
Ordered key-value pairsMap
Frequency countingMap
Private metadata on objectsWeakMap
Tracking object stateWeakSet

⚡ Key Takeaways

🎯 Practice Exercises

EXERCISE 1

Use a Map to count character frequencies in a string. Return a Map of character → count, then find the most frequent character.

EXERCISE 2 — CHALLENGE

Implement a simple LRU (Least Recently Used) cache using a Map. It should have get(key) and set(key, value), and automatically remove the oldest entry when capacity is exceeded.

← Spread & Rest