Skip to content
javascript questions

JavaScript · 10 of 10senior~1 min

What are WeakMap and WeakSet and when would you use them?

#core#memory

WeakMap and WeakSet

Weak collections hold weak references to their keys/values - meaning they don't prevent garbage collection.

WeakMap

js
const weakMap = new WeakMap(); let user = { name: 'Alice' }; weakMap.set(user, { sessionData: '...' }); weakMap.get(user); // { sessionData: '...' } user = null; // object can now be garbage collected // weakMap entry is automatically removed

Constraints:

  • Keys must be objects (or non-registered symbols since ES2023), not primitives.
  • Not iterable - no .forEach, no .size.
  • Only .get, .set, .has, .delete.

WeakSet

js
const visited = new WeakSet(); function process(node) { if (visited.has(node)) return; // already processed visited.add(node); // ... }

When to use

Storing metadata about objects without preventing GC

js
const cache = new WeakMap(); function process(element) { if (cache.has(element)) return cache.get(element); const result = heavyComputation(element); cache.set(element, result); return result; } // when element is removed from DOM and dereferenced, // cache entry is cleaned up automatically

Tracking without memory leaks

js
const listeners = new WeakMap(); // safe to store per-element event data - cleans up with the element

vs regular Map/Set

MapWeakMap
Key typesAnyObjects only
Prevents GCYesNo
IterableYesNo
Memory leak riskYesNo

WeakMap is ideal for private data associated with DOM nodes or class instances - when the object goes away, the associated data disappears automatically.

updated

did you know it?