← Back to JavaScript, page 9

javascript-0177 · Hard senior

Why do the specification and engine authors advise against relying on WeakRef and FinalizationRegistry, and what are they safe to use for?

A WeakRef lets an object be collected, but when that happens is up to the engine, so code must work when collection never happens and when it happens at any point between turns. An object stays alive for the rest of the current job once you deref it, and finalization callbacks may run late or never. Use them only for optional optimization such as caches, never for correctness or required cleanup.

Full answer

new WeakRef(target) holds the target without keeping it alive. ref.deref() returns the target, or undefined if it was collected. FinalizationRegistry lets you register a callback that may run after a target was collected, with a held value you chose.

The guarantees are weak on purpose:

  • There is no guarantee that a collection happens at all. A short script, a small heap, or an engine choice means the target may live until the process exits. Callbacks might never run.
  • Within one synchronous job, a target that was returned from deref() or created is kept alive until the end of that job. That keeps program behavior consistent: ref.deref() === ref.deref() is true within one turn. So tests that create, drop, and check in the same turn never see a collection.
  • Finalization callbacks run in a separate task after collection, with no promised delay and no promised order. The target is gone when the callback runs, which is why you can only use the held value, and the held value must not reference the target or it keeps the target alive.
  • The behavior differs between engines, versions, and settings, and also between a debug run and production. Code that passes locally can fail in production.
  • Cycles through the registry or held values leak. Unregister tokens help you stop callbacks when you clean up by hand.
  • WeakRef can only target objects and non-registered symbols. A string, number, or Symbol.for symbol throws a TypeError.

Good uses: an optional cache where the value can be rebuilt (WeakRef to a parsed result keyed by a string), mapping DOM nodes to expensive data when a WeakMap is not enough because you need to iterate, and leak detection in tests (with --expose-gc and a wait).

Bad uses: closing file handles, sockets, or locks (use try/finally, using, or explicit close()), counting live objects for business logic, and releasing external resources that must be freed at a known time.

A WeakMap is the better first choice when you just need to attach data to an object without keeping it alive. Reach for WeakRef only for the case that needs a key that is a string, such as a cache keyed by id.

javascript
const registry = new FinalizationRegistry((held) => finalized.push(held));
const finalized = [];
const tick = () => new Promise((resolve) => setTimeout(resolve, 20));

function makeCache() {
  const refs = new Map();
  return {
    set(key, value) {
      refs.set(key, new WeakRef(value));
    },
    get(key) {
      const value = refs.get(key)?.deref();
      if (value === undefined) refs.delete(key);
      return value;
    },
    size: () => refs.size,
  };
}

(async () => {
  let target = { big: new Array(1000).fill('data') };
  const ref = new WeakRef(target);
  registry.register(target, 'target was collected');

  console.log('same turn, deref twice is stable:', ref.deref() === ref.deref());
  target = null;
  global.gc();
  console.log('same turn after gc, still alive:', ref.deref() !== undefined);

  await tick();
  global.gc();
  await tick();
  console.log('later turn after gc, collected:', ref.deref() === undefined);
  console.log('finalizer ran later:', finalized);

  const cache = makeCache();
  cache.set('user:1', { name: 'Asha' });
  console.log('cache size before gc:', cache.size());
  await tick();
  global.gc();
  await tick();
  console.log('cache lookup after gc:', cache.get('user:1'), '| size:', cache.size());

  for (const bad of ['text', 42, Symbol.for('registered')]) {
    try {
      new WeakRef(bad);
    } catch (error) {
      console.log('WeakRef of', typeof bad, '->', error.name);
    }
  }
  console.log('WeakRef of a local symbol works:', new WeakRef(Symbol('local')).deref() !== undefined);
})();

Run with Node.js v24.22.1 using the --expose-gc flag as js-177.js; two runs gave identical output. Output: same turn, deref twice is stable: true same turn after gc, still alive: true later turn after gc, collected: true finalizer ran later: [ 'target was collected' ] cache size before gc: 1 cache lookup after gc: undefined | size: 0 WeakRef of string -> TypeError WeakRef of number -> TypeError WeakRef of symbol -> TypeError WeakRef of a local symbol works: true

Key points

  • Collection time is not guaranteed and may never happen; code must stay correct either way.
  • A deref'd or created target stays alive until the end of the current job.
  • Finalization callbacks are late, unordered, and optional; the held value must not reference the target.
  • Safe for optional caches and diagnostics, never for required cleanup.
  • Prefer WeakMap for attaching data; use try/finally or explicit close for resources.

Common mistakes

  • Using FinalizationRegistry to release resources that must be released.
  • Testing collection in the same synchronous turn, where the target is kept alive.
  • Holding the target inside the held value, which keeps it alive forever.
  • Using WeakRef where a WeakMap would be simpler and safer.

Follow-ups

  • How does a WeakMap differ from a Map of WeakRefs?
  • What does the unregister token do?
  • How would you test for a memory leak in a unit test?

Tips

  • Lead with "no guarantee it ever happens".
  • Mention the keep-alive until the end of the job rule.
  • Offer WeakMap, explicit close, and try/finally as the better tools.