Keys that do not prevent collection
A normal Map keeps its keys alive, since the map itself references them. A WeakMap holds its keys weakly, meaning a key being present in the map does not stop the garbage collector from reclaiming it once nothing else points to that object.
- Keys must be objects, not primitives.
- When the key object becomes unreachable elsewhere, its entry disappears.
- You cannot enumerate a WeakMap or read its size.
Why weakness helps
WeakMap is ideal for attaching private data or metadata to objects you do not own. The data lives exactly as long as the object does, with no manual cleanup.
- Cache per object results without leaking when objects go away.
- Store private state keyed by an instance.
- Avoid the leak of a Map that pins every key forever.
The lack of iteration is the price of this safety, because exposing the keys would let you observe collection timing. Reach for WeakMap whenever the lifetime of your data should follow the lifetime of an object.
Key idea
A WeakMap ties entry lifetime to the key object, so data is reclaimed automatically and cannot accidentally pin objects in memory.