Difficulty: Intermediate
What are WeakMap and WeakSet in JavaScript, and how do they differ from Map and Set in terms of keys, iteration and garbage collection?
WeakMap is a key-value collection whose keys must be objects (or non-registered symbols since ES2023), and it holds those keys weakly: if nothing else in the program references a key, the garbage collector can reclaim it and the entry disappears. WeakSet is the same idea for a set of objects. Because entries can vanish at any time, neither collection is iterable and neither has a size, which is the main practical difference from Map and Set.
A normal Map keeps a strong reference to every key. If you use a DOM node as a key and later remove the node from the page, the Map still keeps it alive, so the node and everything it points to leaks until you call delete.
A WeakMap does not count as a reference for garbage collection purposes. Once the last strong reference to the key object is gone, the key, and the value associated with it, become eligible for collection. The value is held strongly only as long as the key is alive. This structure is called an ephemeron.
| Feature | Map / Set | WeakMap / WeakSet |
|---|---|---|
| Key types | Any value, including primitives | Objects and non-registered symbols only |
| Reference to key | Strong | Weak |
Iteration (for...of, keys(), forEach) | Yes | No |
size and clear() | Yes | No |
| Methods | get, set, has, delete, and more | get, set, has, delete (WeakSet: add, has, delete) |
| Typical use | General lookup tables, caches you control | Metadata attached to objects you do not own |
The lack of iteration is deliberate. If you could list the keys, the result would depend on when the garbage collector last ran, which would make programs non-deterministic.
#private fields existed, libraries stored private state in a module-level WeakMap keyed by this. Babel and TypeScript still compile #private fields to WeakMaps when targeting older runtimes.WeakSet of objects already processed, for detecting cycles in a deep clone or deep equality check.WeakSet of instances created by your factory lets you check "was this created by me?" without adding a visible property.TypeError: Invalid value used as weak map key.WeakMap when you need to list or count entries. If you need iteration, you need a Map plus explicit cleanup.WeakMap with WeakRef. WeakRef (ES2021) is a weak reference to a single object that you can deref(), and FinalizationRegistry lets you run a callback after collection. Both are lower level and the spec authors advise avoiding them unless you really need them.const privateState = new WeakMap();
class Wallet {
constructor(ownerId) {
privateState.set(this, { ownerId, balanceInPaise: 0 });
}
deposit(paise) {
privateState.get(this).balanceInPaise += paise;
}
get balance() {
return privateState.get(this).balanceInPaise / 100;
}
}
const w = new Wallet('user_42');
w.deposit(25050);
console.log(w.balance);
console.log(Object.keys(w));
// When `w` becomes unreachable, its WeakMap entry can be collected too.
The state is invisible on the instance and is tied to the instance's lifetime. This is the pattern compilers use to downlevel #private fields.
function deepClone(value, seen = new WeakMap()) {
if (value === null || typeof value !== 'object') return value;
if (seen.has(value)) return seen.get(value); // cycle: reuse clone
const copy = Array.isArray(value) ? [] : {};
seen.set(value, copy);
for (const key of Object.keys(value)) {
copy[key] = deepClone(value[key], seen);
}
return copy;
}
const user = { name: 'Asha' };
user.self = user; // circular reference
const clone = deepClone(user);
console.log(clone.self === clone);
console.log(clone === user);
A WeakMap remembers which objects have already been cloned, so circular references map to the same copy instead of recursing forever. When the clone call finishes, the tracking map holds nothing alive.
WeakMap, WeakSet, Garbage Collection, Weak References, Memory Management