MediumModern JS📖 Theory Question

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

💡

Hint

Keys are weakly held — objects can be GC'd; no iteration, no size — use for private metadata

Full Answer

WeakMap/WeakSet hold weak references to their keys/entries. The garbage collector can collect the referenced object — the entry is automatically removed. Keys must be objects.

// WeakMap — per-object cache that doesn't prevent GC
const cache = new WeakMap();

function process(user) {
  if (cache.has(user)) return cache.get(user); // cache hit
  const result = expensiveCompute(user);
  cache.set(user, result);
  return result;
}
// When user object is GC'd → cache entry vanishes automatically
// No manual cleanup needed!

// WeakSet — track objects without preventing GC
const processing = new WeakSet();
async function handleOnce(obj) {
  if (processing.has(obj)) return; // already running
  processing.add(obj);
  await doWork(obj);
  processing.delete(obj);
}

// WeakMap for private class fields (pre-#private syntax)
const _private = new WeakMap();
class Secure {
  constructor() { _private.set(this, { secret: 42 }); }
  getSecret() { return _private.get(this).secret; }
}

Key limitation: No .size, no iteration, no .keys()/.values(). You can't see what's in them — only access by key.

💡 WeakMap is perfect for: memoization caches keyed by object identity, private object metadata, DOM element data. The key insight: it doesn't extend the lifetime of the key object.

More Modern JS Questions

MediumWhat are generators and when would you use them?EasyWhat is optional chaining (?.) and nullish coalescing (??)?EasyWhat are tagged template literals and what are they used for?EasyExplain destructuring for objects and arrays — including defaults, renaming, rest, and nesting.

Practice this in a timed sprint →

5 free questions, no signup required

⚡ Start Sprint