Advertisement
Advanced JavaScript, Map, Set, WeakMap & WeakSet

Why can't you use WeakMap for caching results keyed by primitive values like strings or numbers?

Short answer

WeakMap keys must be objects (or, more recently, Symbols) specifically because weak references only make sense for garbage-collectable heap objects — primitives are immutable values, not references, so there's no 'object' for the GC to reclaim and the weak-reference mechanism…

Save JavaScript mock interview
Advertisement
AModel answer
WeakMap keys must be objects (or, more recently, Symbols) specifically because weak references only make sense for garbage-collectable heap objects — primitives are immutable values, not references, so there's no 'object' for the GC to reclaim and the weak-reference mechanism doesn't apply.
const cache = new WeakMap();
// cache.set('key', 'value'); // TypeError: Invalid value used as weak map key
Real-world example
Realizing a memoization cache needs a regular Map (not WeakMap) when the cache keys are strings or numbers rather than objects.
Likely follow-ups
  • What is the recently-added registered Symbol behavior that allows Symbols as WeakMap keys?
Related topics