← Lessons

quiz vs the machine

Gold1380

Frontend

WeakMap and Memory

WeakMap holds keys weakly so entries vanish when nothing else references the key.

4 min read · core · beat Gold to climb

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.

Check yourself

Answer to earn rating on the learn ladder.

1. What can be used as a WeakMap key?

2. What happens when a WeakMap key is no longer referenced elsewhere?

3. Why can you not enumerate a WeakMap?