Question presented to candidate: "Why would you reach for a WeakMap instead of a regular Map to attach some private metadata to a set of objects? What real constraints does WeakMap have that a regular Map doesn't?"
What a strong answer should cover:
- 📌 Interview term:
WeakMap/WeakSet— collections that hold their keys (WeakMap) or values (WeakSet) with weak references, meaning the JavaScript engine's garbage collector can reclaim that object's memory once nothing else in the program references it, even though the WeakMap/WeakSet itself still technically "contains" it. - 📌 Interview term: object-only keys/values — verified directly: a
WeakMap/WeakSetgenuinely throws a realTypeError("Invalid value used as weak map key" / "...weak set") for a string, number, or registered symbol (Symbol.for(...)) — only objects, and plain (non-registered)Symbols, are accepted. - 📌 Interview term: no enumeration — verified directly: neither has a real
.sizeproperty, a realSymbol.iterator, nor a real.forEach— they are genuinely not iterable and cannot be inspected as a whole, only queried for one specific key/value at a time (.get/.has). - A precise answer names the real, practical use case this constraint enables: attaching private, per-object metadata (like a cache entry, or "has this been processed") that automatically disappears when the original object is garbage collected, without the WeakMap itself artificially keeping that object alive — verified directly with a real "process each object only once" pattern.
- A precise answer names the direct contrast with a regular
Map: verified directly, a regularMapgenuinely DOES have.sizeand genuinely IS iterable — the exact featuresWeakMapdeliberately omits specifically to make weak referencing and non-enumeration reliable.
Clarifying questions expected:
- None — this is a definitional/technical question; naming the object-only constraint AND the no-enumeration constraint together, with the real reason both exist, is the strong signal.
Code / implementation expected: Yes — showing the real TypeError for a primitive key, plus the missing .size/iterability, demonstrates genuine understanding beyond "it's like Map but weak."