AceDevHub
Intermediate JavaScript Interview QuestionsIntermediateConcept

JavaScript · Question 64

What are WeakMap and WeakSet, and why are they useful for object-associated metadata?

Direct answer

Weak collections hold their keys/items weakly, so their presence does not by itself keep otherwise unreachable keys alive; this makes them useful for metadata and caches tied to object lifetime, and they intentionally do not expose normal enumeration.

A common use case is associating metadata with DOM nodes or application objects without forcing those objects to stay alive solely because the metadata table still exists.

  • WeakMap associates garbage-collectable keys with arbitrary values.
  • WeakSet tracks garbage-collectable values without mapping each one to another value.
  • Weak collections do not provide normal iteration or a reliable size because exposing liveness would make garbage-collection timing observable in problematic ways.
  • If you need to enumerate every entry, a normal Map or Set is the appropriate structure.

For most interviews, “WeakMap keys are objects” is the familiar model. Modern ECMAScript also permits certain non-registered Symbols as weakly held keys; the core concept is that the key must be garbage-collectable.