Skip to content

QuizNot attempted

WeakMap

Why use a WeakMap to cache data per DOM node?
1–4 to choose, Enter to submit
Show answer & explanation

Correct answer:

  • Its keys are held weakly: when the node is removed and unreferenced, the entry can be garbage-collected
  • WeakMap keys are held weakly: once the node is removed and nothing else references it, the node and its cache entry can be garbage-collected.
  • Not 'faster than Map': it isn't meaningfully faster.
  • Not iterable in insertion order: WeakMaps aren't iterable at all (entries can vanish at any time).
  • Not JSON-serialisable: it stringifies to {}.
  • A plain Map would keep removed nodes alive forever.