← Back to JavaScript, page 2

javascript-0039 · Hard senior

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

WeakMap and WeakSet hold their keys (objects or non-registered symbols) weakly, so an entry does not keep the key alive and disappears when the key is garbage collected. They cannot be iterated and have no size. WeakRef holds a weak pointer to one object, and FinalizationRegistry can run a callback after collection, but collection timing is never guaranteed.

Full answer

A normal Map keeps strong references to its keys, so a key stays in memory as long as the map exists. A WeakMap allows the key to be collected if nothing else refers to it, and then the entry vanishes automatically. Keys must be objects or non-registered symbols. A primitive key throws a TypeError.

Because entries can disappear at any time, the specification does not expose them. A WeakMap has only get, set, has, and delete, and a WeakSet has add, has, and delete. There is no iteration, no size, and no clear.

The best use is attaching extra data to an object you do not own without keeping that object alive. Examples are per-element data in a UI library, a cache of computed results keyed by an object, and truly private data keyed by the instance. Marking objects as "already visited" in a graph walk with a WeakSet is another use.

WeakRef wraps a single object. ref.deref() returns the object if it is still alive or undefined if it was collected. It suits optional caches of large objects. FinalizationRegistry lets code register a callback to run after an object is collected, for example to free an external resource.

These tools have a sharp edge: garbage collection is not predictable. The engine may delay collection, collect in a different order, or not collect before the program exits. Code must work correctly whether or not the callback ever runs, and must never depend on it for core logic. Always check the result of deref().

javascript
const metadata = new WeakMap();

function track(element) {
  const info = metadata.get(element) ?? { clicks: 0 };
  info.clicks += 1;
  metadata.set(element, info);
  return info.clicks;
}

const button = { id: 'save' };
console.log(track(button), track(button));
console.log(metadata.has(button), typeof metadata.size, typeof metadata[Symbol.iterator]);

try {
  metadata.set('primitive', 1);
} catch (error) {
  console.log('primitive key:', error.name);
}

const privateData = new WeakMap();
class Account {
  constructor(balance) {
    privateData.set(this, { balance });
  }
  get balance() {
    return privateData.get(this).balance;
  }
}
const account = new Account(500);
console.log(account.balance, Object.keys(account));

const visited = new WeakSet();
const nodeA = { name: 'A' };
visited.add(nodeA);
console.log(visited.has(nodeA), visited.has({ name: 'A' }));

const bigObject = { data: new Array(10).fill(0) };
const ref = new WeakRef(bigObject);
console.log(ref.deref() === bigObject); // still strongly referenced here, so it is alive

const registry = new FinalizationRegistry((label) => {
  console.log('collected:', label); // may run at any time later, or never
});
registry.register(bigObject, 'bigObject');
console.log('program does not depend on the callback');

Run with Node.js v24.22.1 as js-39.js; two runs gave identical output. Output: 1 2 true undefined undefined primitive key: TypeError 500 [] true false true program does not depend on the callback

Key points

  • Weak collections do not keep their keys alive; entries vanish after collection.
  • Keys must be objects or non-registered symbols.
  • No iteration, size, or clear on WeakMap and WeakSet.
  • WeakRef.deref() may return undefined; FinalizationRegistry callbacks may never run.
  • Use for metadata, caches, and private data tied to an object lifetime.

Common mistakes

  • Using a WeakMap and expecting to list its entries or count them.
  • Relying on a FinalizationRegistry callback to run on schedule.
  • Using a WeakRef for data that must exist, without handling undefined from deref().
  • Trying to use strings or numbers as WeakMap keys.

Follow-ups

  • Why is there no size property on a WeakMap?
  • How does a WeakMap differ from private class fields for private data?
  • Why does a WeakRef target stay alive for the rest of the current job after deref()?

Tips

  • Lead with "does not keep the key alive". The rest follows from that.
  • Give one use case, such as metadata attached to DOM elements.
  • Say clearly that garbage collection timing is unspecified, and that you never depend on it.