Sub topic 3
WeakMap and WeakSet: Where Weakness Started
Weak references reached JavaScript before WeakRef. ES2015 added WeakMap and WeakSet, two collections that hold their entries without keeping the keys alive. Knowing exactly what these collections guarantee, and what they cannot do, explains why WeakRef and FinalizationRegistry were added later.
This chapter assumes you know how Map and Set work, that you are comfortable with object references and closures, and that you have read the earlier chapters on reachability and on strong versus weak references.
The Problem WeakMap Solves
Suppose you want to attach extra data to objects you don't own, such as DOM nodes, objects from a library, or request objects in a server. A plain Map works, but it creates a leak:
const metadata = new Map();
function tag(obj, info) {
metadata.set(obj, info);
}
let node = { id: 'button-1' };
tag(node, { clicks: 0 });
node = null;
// The object is still reachable through metadata's key,
// so it can never be collected until we call metadata.delete().The Map holds a strong reference to every key. Your side table now decides how long the objects live, which is the wrong way round. You wanted to describe the objects, not own them.
WeakMap fixes this by holding its keys weakly:
const metadata = new WeakMap();
let node = { id: 'button-1' };
metadata.set(node, { clicks: 0 });
console.log(metadata.get(node)); // { clicks: 0 }
node = null;
// The only remaining reference to the object is the WeakMap key.
// The object, and its entry, are now eligible for collection.Once nothing else references the key, the collector may remove both the key and its value. You never see the removal happen. The entry simply stops existing.
How a WeakMap Entry Works Internally
A WeakMap entry is an ephemeron. An ephemeron is a key–value pair where the value stays reachable only while the key is reachable from somewhere else. The garbage collector treats the entry roughly like this:
- The map does not count as a reason to keep the key alive.
- If the key is reachable through some other path, the value is treated as reachable too.
- If the key is not otherwise reachable, the key and the value can both be collected.
The ephemeron rule has an effect that surprises many people: a value that references its own key does not keep the key alive. With a Map plus a cycle you would leak. With a WeakMap you don't:
const owners = new WeakMap();
let user = { name: 'Ada' };
owners.set(user, { owner: user, createdAt: Date.now() });
user = null;
// The value points back at the key, but the value is only
// reachable through the key's entry. Both can be collected.A naive "weak keys, strong values" implementation would get this wrong. The value would hold the key, the map would hold the value, and nothing would ever be freed. Engines implement ephemerons specially to avoid this.
The API Is Deliberately Small
| Collection | Methods | Missing compared to Map/Set |
|---|---|---|
| `WeakMap` | `get`, `set`, `has`, `delete` | `size`, `clear`, `keys`, `values`, `entries`, `forEach`, iteration |
| `WeakSet` | `add`, `has`, `delete` | `size`, `clear`, `values`, `forEach`, iteration |
The missing methods are a design decision. If you could iterate a WeakMap or read its size, your program could watch entries disappear and infer when the collector ran. Garbage collection timing varies between engines, between runs, and with memory pressure. Exposing it would make programs behave differently in different environments. Hiding it means a WeakMap gives the same answers no matter when, or whether, the collector runs: for any key you still hold, get returns what you stored.
WeakRef and FinalizationRegistry give up that property on purpose, and that is why the later chapters spend so much time on nondeterminism.
What Can Be a Key
Weak collections need keys whose identity can't be recreated. Primitives such as strings and numbers fail this test, because 'abc' written twice is the same value. If 'abc' were a weak key, the entry could never safely disappear, since anyone could write 'abc' again and expect to find it.
const wm = new WeakMap();
try {
wm.set('abc', 1);
} catch (err) {
console.log(err instanceof TypeError); // true
}
const ws = new WeakSet();
try {
ws.add(42);
} catch (err) {
console.log(err instanceof TypeError); // true
}Objects, including arrays, functions, and class instances, are always valid. Since ES2023, non-registered symbols (those created with Symbol()) are valid too. Registered symbols from Symbol.for() are not, because the same registered symbol can be fetched again from the global registry. A later chapter covers the exact rules, which also apply to WeakRef targets.
WeakSet: Membership Without Ownership
A WeakSet is a WeakMap with no values. It answers one question: have I seen this object, and is it still alive? Common uses are branding objects and tracking visited nodes.
Branding means marking objects your code created so you can check them later, without adding a visible property:
const genuine = new WeakSet();
class Token {
constructor(value) {
this.value = value;
genuine.add(this);
}
static isGenuine(obj) {
return genuine.has(obj);
}
}
const real = new Token('x');
const fake = { value: 'x' };
console.log(Token.isGenuine(real)); // true
console.log(Token.isGenuine(fake)); // falseCycle detection during a recursive walk is another good fit:
function deepCount(value, seen = new WeakSet()) {
if (value === null || typeof value !== 'object') return 1;
if (seen.has(value)) return 0;
seen.add(value);
let count = 1;
for (const child of Object.values(value)) {
count += deepCount(child, seen);
}
return count;
}
const a = { name: 'a' };
a.self = a;
console.log(deepCount(a)); // 2: the object itself and the 'a' stringA plain Set would also work here, because seen is discarded when the walk ends. WeakSet matters when the set lives for a long time, such as a module-level registry of instances.
Typical WeakMap Patterns
Per-object memoization. Cache a result computed from an object, and let the cache entry die with the object:
const areaCache = new WeakMap();
function expensiveArea(shape) {
if (areaCache.has(shape)) return areaCache.get(shape);
const result = shape.width * shape.height; // stand-in for real work
areaCache.set(shape, result);
return result;
}
const rect = { width: 3, height: 4 };
console.log(expensiveArea(rect)); // 12, computed
console.log(expensiveArea(rect)); // 12, cachedPrivate state. Before #private fields existed, libraries kept instance data in a module-scoped WeakMap. You will still see this in older code, and it remains useful for adding hidden state to objects whose class you don't control.
const secrets = new WeakMap();
class Account {
constructor(pin) {
secrets.set(this, { pin });
}
check(pin) {
return secrets.get(this).pin === pin;
}
}
const acct = new Account('1234');
console.log(acct.check('1234')); // true
console.log(Object.keys(acct)); // []Common Errors
- Expecting the entry to vanish while you still hold the key. If any variable, closure, event listener, or other collection references the key, the entry stays. Weak collections only help when the key really becomes unreachable.
- Reaching for a
WeakMapwhen you need to list entries. If you need to enumerate or count tracked objects, a weak collection cannot do it. You need aMapwith explicit removal, orWeakRefwith its trade-offs. - Using primitive IDs as keys. Keying by
user.id(a string) instead ofuserthrows onset. Switching to aMapto make the error go away brings the leak back. - Assuming the value is weak. Values are held strongly for as long as the key lives. A large value attached to a long-lived key stays in memory.
The Gap That Led to WeakRef
Every weak collection is weak in its keys. The key must be an object you already have in order to look anything up. That leaves a common need uncovered: looking up an object by a primitive key, such as a URL, a file path, or a database ID, without keeping the object alive.
// What we want: id -> object, where the object can still be collected.
// WeakMap can't do it: 'user-17' is a string and can't be a key.
// Map can do the lookup, but it holds the object strongly.This is a weak-value map, and nothing in ES2015 can build one. It needs a reference you can hold, ask "is it still there?", and get either the object or nothing. That is WeakRef. Once entries can disappear, you also need a way to remove the leftover string keys, which is FinalizationRegistry. Both features accept the nondeterminism that WeakMap hides, and the next chapters explain how to live with it.
| Need | Tool |
|---|---|
| Attach data to an object without owning it | `WeakMap` |
| Mark or track objects without owning them | `WeakSet` |
| Look up objects by a primitive key without owning them | `WeakRef` inside a `Map` (covered later) |
| Enumerate or count tracked objects | `Map`/`Set` with explicit deletion |
Exercise
You store cache.set(obj, { source: obj, size: 1e6 }) in a WeakMap, then drop every other reference to obj. Can the entry be collected even though the value refers back to the key? Explain why.
Show answer
Yes. WeakMap entries are ephemerons: the value is reachable only through the key's entry, and the entry gives no reachability to the key. With no outside path to obj, both the key and the value (including its back-reference) are unreachable and may be collected.
Exercise
Why does WeakMap have no size property or iteration methods, and why does new WeakMap().set('id-1', {}) throw?
Show answer
Exposing size or iteration would let a program see when the collector removed entries, which would make GC timing observable and behavior differ between engines and runs. The set call throws a TypeError because a string is a primitive that can be recreated at any time, so it cannot serve as a weakly held key; only objects and non-registered symbols are allowed.
Exercise
You need a map from user ID strings to large User objects, and the objects should be collectable when the rest of the app stops using them. Which of Map, WeakMap, or WeakSet fits, and if none does, what is missing?
Show answer
None fits. A Map holds the User objects strongly, so they leak. WeakMap and WeakSet need the object as the key, but the keys are strings. The missing piece is a weak value: an entry that holds the object without keeping it alive and reports when it is gone. That requires WeakRef, usually paired with FinalizationRegistry to remove stale keys.