What is WeakMap?

A WeakMap is a key-value collection whose keys must be objects (or non-registered symbols) and are held weakly: an entry does not stop its key from being garbage-collected, and once the key is gone the entry disappears automatically.

Differences from Map

MapWeakMap
KeysAny valueObjects (and non-registered symbols) only
Keeps keys aliveYesNo
Iterable / sizeYesNo
Methodsget, set, has, delete, clear, iterationget, set, has, delete

It cannot be iterated or sized because its contents can change whenever the garbage collector runs.

Use cases

  • Attaching data to objects you don't own (DOM nodes, library objects) without modifying them and without causing leaks.
  • Caching results per object: memoise computations keyed by an object; the cache entry dies with the object.
  • Private data for classes (the pre-#private technique).
  • Tracking which objects have already been processed.

When to use something else

  • Need to list or count entries, or use primitive keys: use Map.
  • Just need to remember objects (no value): use WeakSet.
  • Need to hold an object weakly and check later whether it is still alive: WeakRef.

Code example

js
1// Cache expensive per-object results without leaking memory
2const sizeCache = new WeakMap();
3function expensiveSize(obj) {
4 if (sizeCache.has(obj)) return `${sizeCache.get(obj)} (cached)`;
5 const size = JSON.stringify(obj).length; // pretend this is expensive
6 sizeCache.set(obj, size);
7 return size;
8}
9
10let report = { rows: Array.from({ length: 100 }, (_, i) => ({ i })) };
11console.log(expensiveSize(report)); // computed
12console.log(expensiveSize(report)); // "... (cached)"
13report = null; // the cache entry can be collected along with the object
14
15// Attach metadata to objects you don't own
16const clickCounts = new WeakMap();
17const button = { id: "buy" }; // imagine a DOM element
18clickCounts.set(button, (clickCounts.get(button) ?? 0) + 1);
19clickCounts.set(button, clickCounts.get(button) + 1);
20console.log(clickCounts.get(button)); // 2
21
22// Keys must be objects
23try {
24 new WeakMap().set("text", 1);
25} catch (e) {
26 console.log(e.name); // TypeError
27}
28
29// No size or iteration
30console.log(typeof new WeakMap().size, typeof new WeakMap()[Symbol.iterator]); // undefined undefined

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.

Open in study app