Script Valley
JavaScript: The Complete Language
Advanced JavaScript PatternsLesson 6.5

WeakMap, WeakSet, and memory management in JavaScript

WeakMap, WeakSet, garbage collection, strong vs weak references, use cases private data caching, Map vs WeakMap differences, memory leaks patterns, FinalizationRegistry

Weak References and Garbage Collection

Regular Map holds strong references — objects stored as keys cannot be garbage collected even after all other references are gone. WeakMap holds weak references, allowing the garbage collector to reclaim objects automatically when nothing else references them. This prevents entire classes of memory leaks.

WeakMap — Automatic Cleanup

const cache = new WeakMap();

function processElement(element) {
  if (cache.has(element)) {
    return cache.get(element); // return cached result
  }
  const result = expensiveComputation(element);
  cache.set(element, result);
  return result;
}
// When the element is removed from the DOM and dereferenced,
// the WeakMap entry is automatically garbage collected.
// No manual cleanup needed.

WeakMap for Private Instance Data

const _private = new WeakMap();

class Counter {
  constructor() {
    _private.set(this, { count: 0 });
  }
  increment() {
    _private.get(this).count++;
  }
  value() {
    return _private.get(this).count;
  }
}
// Private data is inaccessible outside the module

WeakSet

const seen = new WeakSet();
function processOnce(obj) {
  if (seen.has(obj)) return;
  seen.add(obj);
  doWork(obj);
}

Limitations

WeakMap and WeakSet keys must be objects, never primitives. Neither is iterable — you cannot list entries or check size. This is intentional: iteration would require holding strong references, defeating the purpose. Use a regular Map when you need to enumerate entries.