Advertisement
Intermediate JavaScript, Map, Set, WeakMap & WeakSet

What is a WeakMap and why can't you iterate over its keys?

Short answer

A WeakMap holds its keys weakly, meaning entries don't prevent the garbage collector from reclaiming a key object once there are no other references to it — this makes iteration (or even .size) impossible, since the set of live keys can shrink at any unpredictable moment via GC.

Save JavaScript mock interview
Advertisement
AModel answer
A WeakMap holds its keys weakly, meaning entries don't prevent the garbage collector from reclaiming a key object once there are no other references to it — this makes iteration (or even .size) impossible, since the set of live keys can shrink at any unpredictable moment via GC.
const cache = new WeakMap();
let obj = { id: 1 };
cache.set(obj, 'metadata');
obj = null; // the entry can now be garbage collected automatically
Real-world example
Attaching private metadata to DOM elements without preventing them from being garbage collected when removed from the page.
Likely follow-ups
  • What restrictions does WeakMap place on what can be used as a key?
Related topics