Glossary / WeakMap

WeakMap

WeakMap associates values with object keys without keeping those keys alive solely because of the map. It is useful for metadata and caches whose lifetime should follow an object, such as annotations for DOM nodes or internal data associated with instances. Weakness refers to garbage-collection reachability, not reduced access control.

Semantics and limitations

const metadata = new WeakMap();
function annotate(node, value) { metadata.set(node, value); }

Keys must be objects or supported non-registered Symbols; primitive values such as strings cannot be keys. WeakMap is deliberately not enumerable and provides no size or clear, because exposing its keys would make nondeterministic garbage-collection state observable. It has get, set, has, and delete. Object keys match by identity.

A WeakMap is not a general replacement for Map: use Map when keys must be listed, counted, or primitive. Be cautious about values that point back to keys and surrounding object graphs; understand reachability rather than assuming “weak” means the entire entry is weak. Do not use finalization or collection timing as application logic. Modern support for Symbol keys should be checked against deployment targets.

Interview questions

  1. Why can’t WeakMap be iterated? Its contents could change nondeterministically as keys are collected.
  2. Can strings be keys? No; keys must be objects or supported non-registered Symbols.
  3. Typical use? Metadata tied to an object’s lifetime without preventing its collection.
  4. When use Map? When iteration, size, primitive keys, or explicit clearing is required.

References