Skip to main content

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:

javascript
let user = { name: "Tim" }; // an object in memory user = null; // the reference is lost -> the object is removed by the GC

The 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.

javascript
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 memory

The 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.
javascript
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 automatically

After 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.
javascript
let user = { name: "Tim" }; const weakSet = new WeakSet(); weakSet.add(user); user = null; // the object is removed by the GC // weakSet automatically loses this reference

Key features of WeakMap / WeakSet

PropertyWeakMapWeakSet
KeysObjects onlyObjects only
ValuesAnyNo values
ReferencesWeakWeak
GC clears automaticallyYesYes
Can iterate (for...of)NoNo
Methodsset, get, has, deleteadd, 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

javascript
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 cache

Here we avoided a memory leak: as soon as the user disappears from memory, their cache entry is cleared automatically.


2. Tracking object state

javascript
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

TypeStores objects?GC auto-cleanupCan iterate
MapYesNoYes
WeakMapYesYesNo
SetYesNoYes
WeakSetYesYesNo

Summary

ItemDescription
ProblemRegular collections prevent the GC from removing unused objects
SolutionWeakMap and WeakSet use weak references
BehaviorObjects are removed from the collection automatically during garbage collection
LimitationsCannot iterate, get the size, or list the elements
UsageCaches, temporary data, visited flags, storing metadata

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.