How do WeakMap and WeakSet help the garbage collector?
Reminder: how the garbage collector works
JavaScript uses automatic memory management: the developer does not free memory manually.
An object stays in memory as long as there is at least one reference to it. When no references remain → the garbage collector (GC) removes it.
Example:
let user = { name: "Tim" }; // an object in memory
user = null; // the reference is lost -> the object is removed by the GCThe problem with regular collections (Map, Set)
Regular Map and Set hold references to objects strongly (strong reference).
Even if the object is no longer used anywhere else,
the GC cannot remove it while it is inside a Map or Set.
let user = { name: "Tim" };
const map = new Map();
map.set(user, "data");
user = null;
// the object is still stored in map!
// the GC cannot free the memoryThe result is a memory leak if there are a lot of such objects.
The solution: WeakMap and WeakSet
WeakMap
- Keys are objects only (not strings, not numbers);
- Values can be anything;
- References are "weak" (weak references): if the object is no longer used anywhere else, it is automatically removed from the WeakMap by the garbage collector.
let user = { name: "Tim" };
const weakMap = new WeakMap();
weakMap.set(user, "data");
user = null; // the object is no longer reachable
// the GC will remove both the key and the value from the WeakMap automaticallyAfter the object is removed from memory, the key disappears from the WeakMap.
No manual delete() is needed.
WeakSet
- Stores objects only (no primitives);
- Every entry is a weak reference;
- If an object is no longer used anywhere else, it gets removed from the WeakSet automatically.
let user = { name: "Tim" };
const weakSet = new WeakSet();
weakSet.add(user);
user = null; // the object is removed by the GC
// weakSet automatically loses this referenceKey features of WeakMap / WeakSet
| Property | WeakMap | WeakSet |
|---|---|---|
| Keys | Objects only | Objects only |
| Values | Any | No values |
| References | Weak | Weak |
| GC clears automatically | Yes | Yes |
| Can iterate (for...of) | No | No |
| Methods | set, get, has, delete | add, has, delete |
Why you cannot iterate a WeakMap / WeakSet
Because the browser does not know when the GC will remove a specific object. The GC runs unpredictably, and the contents of such collections can change at any moment.
That's why WeakMap and WeakSet have no methods like:
.size.keys().entries().values()forEach
Real usage examples
1. Storing data "tied" to an object
const cache = new WeakMap();
function getUserData(user) {
if (!cache.has(user)) {
cache.set(user, { name: user.name, time: Date.now() });
}
return cache.get(user);
}
let tim = { name: "Tim" };
console.log(getUserData(tim)); // cache the data
tim = null; // the GC removes the object and its data from the cacheHere we avoided a memory leak: as soon as the user disappears from memory, their cache entry is cleared automatically.
2. Tracking object state
const visited = new WeakSet();
function process(obj) {
if (visited.has(obj)) return; // already processed
visited.add(obj);
// ...do something
}After obj is removed from memory, it disappears from the WeakSet on its own.
Comparison with regular collections
| Type | Stores objects? | GC auto-cleanup | Can iterate |
|---|---|---|---|
Map | Yes | No | Yes |
WeakMap | Yes | Yes | No |
Set | Yes | No | Yes |
WeakSet | Yes | Yes | No |
Summary
| Item | Description |
|---|---|
| Problem | Regular collections prevent the GC from removing unused objects |
| Solution | WeakMap and WeakSet use weak references |
| Behavior | Objects are removed from the collection automatically during garbage collection |
| Limitations | Cannot iterate, get the size, or list the elements |
| Usage | Caches, temporary data, visited flags, storing metadata |
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.