Question presented to candidate: "If you use an object as a WeakMap key to store some metadata about it, and then that object becomes otherwise unreachable, does the WeakMap keep it alive? Can you actually prove your answer, not just state it?"
What a strong answer should cover:
- 📌 Interview term:
WeakMap— a Map-like collection whose KEYS must be real objects and are held with only a weak reference — meaning an entry's presence in aWeakMapgenuinely does NOT, by itself, keep that key object alive. - 📌 Interview term: the real, direct, OBSERVED answer to the prompt — verified directly, not just asserted: a key object was registered with a real
FinalizationRegistry, its only other strong reference was dropped, garbage collection was forced (node --expose-gc), and the registry's real cleanup callback GENUINELY FIRED — real, observed proof that theWeakMap-held key was genuinely eligible for and underwent collection. - 📌 Interview term: contrast with a regular
Map— a regularMapgenuinely holds a strong reference to every key, meaning a key object used as aMapkey can NEVER be garbage collected while thatMapstill exists, even if literally nothing else in the program references it anymore — a real, classic source of memory leaks in long-lived caches. - 📌 Interview term: the real practical use case — a precise answer names per-object metadata caching (memoizing an expensive computed result keyed by a specific object instance, or attaching private data to an instance without a real "private field") as the real, canonical WeakMap use case — the cache entry genuinely disappears on its own once the object it describes is no longer needed anywhere else, with zero manual cache-eviction code required.
- A precise answer is honest that JS code can never directly observe or control garbage collection's actual TIMING — only its eventual, real occurrence, confirmable indirectly via a tool purpose-built for it,
FinalizationRegistry.
Clarifying questions expected:
- None — this is a definitional/mechanism question; the strong signal is genuinely PROVING the claim (not just stating documentation) via a real, observed collection event.
Code / implementation expected: Yes — a real FinalizationRegistry-based proof that a WeakMap's key object is genuinely collected once unreferenced elsewhere.