CodeZettaInterview Hub

JavaScript · Memory Management · Mid-Level · Concept

When would you use WeakMap, WeakSet, and WeakRef?

Short Interview Answer

WeakMap/WeakSet allow GC of keys when no other refs exist — great for metadata; WeakRef/FinalizationRegistry are advanced and easy to misuse.

Detailed Explanation

WeakMap keys must be objects and are held weakly — ideal for private data or associating state with DOM elements without preventing GC. WeakSet similarly tracks object membership weakly. WeakRef gives a weak pointer to an object; FinalizationRegistry schedules cleanup callbacks after GC (not timely/guaranteed for critical logic). Avoid building caches solely on WeakRef without understanding non-determinism. Never use finalizers for resource disposal that must be prompt — use explicit `dispose`/`AbortController`.

Example

const meta = new WeakMap();
function tag(el, info) {
  meta.set(el, info);
}

Interview Tip

Stress that finalizers are not destructors for RAII-style cleanup.

Common Mistake

Using WeakMap with primitive keys (not allowed).

Did you know this answer?