Course contentsShow
← JavaScript
Lesson 1880 of 2,72339. Memory Management and GCFree lesson

WeakMap and WeakSet as Solutions

Using weak references to allow garbage collection of keys while maintaining associated metadata.

WeakMap and WeakSet as Solutions

What You'll Learn

You'll learn how WeakMap and WeakSet allow the garbage collector to reclaim objects even when you're storing metadata about them, preventing memory leaks.

The Problem They Solve

When you store objects as keys in a regular Map or as values in a regular Set, those references prevent garbage collection. Even if everywhere else in your code stops using an object, the Map/Set keeps it alive—creating a memory leak.

WeakMap and WeakSet hold weak references to objects. If an object has no other references in your program, the garbage collector can remove it, and it automatically disappears from the WeakMap/WeakSet too.

When to Use Them

Use WeakMap when:

  • Attaching private metadata to DOM nodes or other objects you don't control
  • Caching computed values keyed by objects
  • You want automatic cleanup when the key object is no longer needed

Use WeakSet when:

  • Tracking objects you've already processed
  • Marking objects as belonging to a group
  • You want automatic cleanup when the object is garbage collected

Key Limitations

  • Keys must be objects (not primitives)
  • Not iterable—you can't loop through entries
  • No .size property or .clear() method

This is by design: since entries can disappear at any time due to garbage collection, iteration wouldn't be reliable.

The Memory Safety Benefit

If you attached event listeners to 1,000 DOM nodes and stored metadata about each in a WeakMap, removing those nodes from the DOM allows them and their metadata to be garbage collected automatically—no manual cleanup needed.

Key Takeaway: Use WeakMap and WeakSet when you need to associate data with objects without preventing those objects from being garbage collected—they're your primary tool for avoiding object-related memory leaks.