Course contentsShow
← Web Development
Lesson 2117 of 2,98238. JavaScript Performance in the BrowserFree lesson

WeakMap and WeakSet for Automatic Cleanup

Learn how weak references allow garbage collection of keys and prevent common caching-related leaks.

WeakMap and WeakSet for Automatic Cleanup

You'll learn how weak references prevent memory leaks by allowing garbage collection of keys that are no longer referenced elsewhere.

What Makes Them "Weak"?

Regular Map and Set hold strong references to their keys. Even if nothing else in your code references an object anymore, a Map will keep it alive in memory forever—a classic memory leak.

WeakMap and WeakSet hold weak references. If an object stored as a key has no other references, JavaScript's garbage collector can automatically remove it—and its associated data disappears too.

The Cleanup Analogy

Think of a regular Map like a museum that never throws anything away. Even if nobody visits an exhibit anymore, it stays forever.

A WeakMap is like a museum that automatically removes exhibits when nobody outside the museum remembers they exist. The moment the last visitor forgets about an artifact, it vanishes.

When to Use Them

WeakMap is perfect for attaching metadata to DOM nodes or objects you don't control:

const nodeMetadata = new WeakMap();

function attachData(element) {
  nodeMetadata.set(element, { clicks: 0, lastSeen: Date.now() });
}

// When the element is removed from DOM and no longer referenced,
// the metadata is automatically garbage collected

WeakSet works for tracking objects without preventing their cleanup:

const processedElements = new WeakSet();

function processOnce(element) {
  if (processedElements.has(element)) return;
  // ...do work...
  processedElements.add(element);
}

Important Limitations

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

Key Takeaway: Use WeakMap and WeakSet when caching or tracking objects you don't own—they automatically clean up when those objects are garbage collected, preventing the "cache that grows indefinitely" leak pattern.