CodePark/ questions / Errors & memory
START PRACTICINGPRACTICE
Frontend question · JavaScript › Errors & memory

What is a WeakMap, how does it relate to garbage collection, and when would you use it?

A WeakMap is a key-value collection that does not keep its keys alive. When nothing else references a key object, the garbage collector can free it, and its entry disappears too.

Keys: they must be objects, or non-registered symbols (symbols not created with Symbol.for). The map holds them weakly.

Limits: entries can disappear at any time. So a WeakMap cannot be looped over, has no size and has no clear. You can only use get, set, has and delete, with a key you already hold.

When to use it: to attach data to objects you do not own, without leaking memory. Examples:

  • caching results per object, like memoizing a function with an object argument
  • storing private data for class instances
  • storing metadata for DOM nodes that should go away when the node is removed

A regular Map would keep those objects alive forever.

Related: WeakSet is the same idea for checking membership. WeakRef gives a weak reference to one single object.

  • WeakMap keys are objects held weakly. Entries disappear when their keys are garbage collected.
  • A WeakMap cannot be looped over and has no size, because its contents depend on GC timing.
  • Use it for per-object caches, private data and DOM metadata.
  • A normal Map with object keys stops those objects from being collected.