Skip to content
WeakRef, WeakMap, WeakSet
step 1/5

Reading — step 1 of 5

Learn

~1 min readProxy and Memory

JavaScript's GC won't collect an object as long as any reference exists. Weak collections let you hold a reference that DOESN'T prevent collection.

WeakMap — keys are objects, weakly held:

javascript

Differences from Map:

  • Keys must be objects (not primitives)
  • Not iterable — no keys(), values(), entries(), forEach
  • No size property
  • Entries can vanish at any time

Use cases:

  • Caching computed data per object: const cache = new WeakMap()
  • Private data: const privateData = new WeakMap(); then privateData.get(this) inside methods
  • DOM event listeners that should clean up when nodes are removed

WeakSet — same idea, no values:

javascript

WeakRef (modern, ES2021) — explicit weak reference to an object:

javascript

FinalizationRegistry — get a callback when an object is GC'd:

javascript

Caveats:

  • GC timing isn't deterministic — never rely on a specific moment
  • Don't use these for critical cleanup (file handles, network connections) — use explicit close()
  • Mostly useful for caches, observers, debugging memory leaks

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…