Map, Set & WeakMap

Specialized collections for unique values and key-value pairs.

Map

Key-value pairs. Any type as a key.

const map = new Map();
map.set("name", "Ada");
map.set(42, "answer");
map.set(true, "yes");

map.get("name");  // "Ada"
map.get(42);      // "answer"
map.size;         // 3

Unlike objects, Map keys can be any type — numbers, booleans, objects, even functions.

1 / 3

Set

Unique values only. No duplicates.

const set = new Set([1, 2, 3, 2, 1]);
// Set {1, 2, 3} — duplicates removed!

set.add(4);    // Set {1, 2, 3, 4}
set.add(2);    // Set {1, 2, 3, 4} — no change
set.size;      // 4

Set automatically deduplicates. Adding an existing value is a no-op.

1 / 3

WeakMap & WeakSet

Garbage-collector friendly. Keys must be objects.

// WeakMap: keys are weakly held
const cache = new WeakMap();

let obj = { data: "important" };
cache.set(obj, "cached result");

obj = null;
// obj is garbage-collected!
// cache entry automatically removed

// Use cases:
// • Private data for class instances
// • Caching without memory leaks
// • DOM node metadata

WeakMap/WeakSet don't prevent garbage collection. Perfect for metadata you don't want to leak memory.

When to Use What

Choose the right collection.

ObjectString/Symbol keys, JSON-compatible, simple config
MapAny key type, frequent add/delete, need size, ordered
ArrayOrdered list, indexed access, duplicates OK
SetUnique values, fast .has() checks, deduplication
WeakMapObject keys, private data, cache without leaks