`WeakRef` and `FinalizationRegistry`

Advanced · 26 min

Holding a reference that doesn't stop garbage collection, running cleanup when an object is collected, and why both are last-resort, non- deterministic tools.

Before thisMemory Management and Garbage Collection

Reversim · 26 min

`WeakRef` and `FinalizationRegistry`

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by ReversimReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • A normal reference to an object is a *strong* reference — holding one, from anywhere, is enough to keep that object alive in memory. `WeakRef` wraps an object in a reference that does not count toward keeping it alive; if nothing else references the object, the garbage collector is still free to reclaim it.
  • You read a `WeakRef`'s target with `.deref()`, which returns the object if it's still alive or `undefined` if it's already been collected — every single access has to handle both outcomes, because you can never assume the thing you wrapped is still there.
  • `FinalizationRegistry` lets you register a cleanup callback that *may* run after an object is garbage collected — useful for releasing an external resource (closing a file handle, disconnecting something) tied to that object's lifetime, but the callback's timing is entirely up to the engine.
  • Neither API gives you a promise of *when* collection happens, or even a guarantee it happens at all before the program exits — the spec deliberately leaves the timing unobservable, which rules out using either one for anything that needs to run reliably, like releasing a resource your program's correctness actually depends on.
  • Both exist to solve one narrow problem: a cache or a registry that needs to reference objects without being the reason those objects never get freed. Reaching for either anywhere else is almost always a sign a different tool (explicit cleanup, `WeakMap`, a lifecycle hook) is the one actually being avoided.

The problem: references that shouldn’t keep things alive

You already know the garbage collector reclaims memory for objects nothing can reach anymore. The catch is that “nothing can reach it” has to mean nothing, including references you only wanted for bookkeeping. Imagine a cache that maps an object to some expensive computed value about it — built with a plain Map. A plain Map holds a strong reference to every key it stores, which means every object you’ve ever cached stays alive for as long as the Map exists, whether or not your program still cares about that object. You’ve built a cache; you’ve also built a memory leak that grows forever.

WeakMap, from earlier in this roadmap, solves the common version of this — a key/value association that doesn’t keep the key alive. WeakRef and FinalizationRegistry solve the narrower cases WeakMap can’t reach: when you need to hold a weak reference to a single object directly (not as a map key), or when you need to actually react when something gets collected, not just avoid blocking its collection.

WeakRef: a reference that doesn’t vote

A WeakRef wraps an object in a handle that doesn’t count toward keeping that object alive. If every other, ordinary reference to the object goes away, the garbage collector is free to reclaim it — the WeakRef doesn’t object.

let cacheEntry = new WeakRef(expensiveObject);

// later, maybe much later:
const obj = cacheEntry.deref();
if (obj) {
  // still alive — use it
} else {
  // already collected — recompute or skip
}

.deref() is the only way to get the object back out, and it can hand you undefined at any point after the real object stops being reachable elsewhere. That if (obj) check isn’t defensive paranoia — it’s mandatory, because there’s no version of this API where you get to assume the thing you wrapped is still there.

FinalizationRegistry: cleanup, maybe, eventually

WeakRef lets you check on an object; FinalizationRegistry lets you ask to be told when one gets collected, by registering a callback alongside it:

const registry = new FinalizationRegistry((heldValue) => {
  console.log(`cleaned up: ${heldValue}`);
});

function track(obj, label) {
  registry.register(obj, label);
}

Once obj is garbage collected, the engine may eventually call the callback with the held value you registered. This sounds like a destructor from a language with manual memory management, and it’s worth resisting that comparison — a destructor runs deterministically, the moment an object is freed. A FinalizationRegistry callback runs on the engine’s schedule, possibly much later, possibly not before your program exits, and the spec is explicit that none of that timing is something your code is allowed to depend on.

This is a last resort, not a strategy

Both APIs exist for one narrow shape of problem: something that needs to reference objects — for a cache, a side-table of metadata — without that reference itself being the reason those objects never get freed. That’s it. They are not a general tool for managing memory, and the spec’s own language around them leans hard on words like “may” for exactly this reason — a conforming engine is allowed to never call your FinalizationRegistry callback at all.

The video embedded here makes this case directly: it’s a talk built around the question of why garbage collection, despite being automatic, still leaves real scenarios where you need finer control — and it walks through WeakRef and FinalizationRegistry with concrete usage examples and the best practices around them, including where people reach for these APIs when they shouldn’t. That framing matters more than the API surface itself here — knowing when not to use this is most of the lesson.

If you ever find yourself wanting a FinalizationRegistry callback to reliably release a resource — close a connection, release a lock, flush a buffer — stop and look for an explicit close()/dispose() method instead, one your code calls on purpose, at a point you control. Treat a FinalizationRegistry entry, if you use one at all, as a backstop for cases where that explicit call got missed — never as the primary mechanism.

Where this fits

This lesson assumes garbage collection already makes sense — reachability, what keeps an object alive, why leaks happen despite automatic collection. WeakRef and FinalizationRegistry are the sharpest, least-needed tools in that whole area: genuinely useful for a small number of library- and cache-authoring problems, and a bad default answer to almost everything else. Knowing they exist, and knowing to reach past them first, is the realistic amount of this to carry forward.

Check yourself

  1. 01What does it mean for a `WeakRef` to hold a "weak" reference, and how is that different from an ordinary variable pointing at the same object?

    An ordinary reference is strong — as long as any strong reference to an object exists anywhere in the program, the garbage collector will not reclaim it. A `WeakRef` wraps an object without contributing to that count at all; if every *other* reference to the object disappears, the garbage collector can collect it even while a `WeakRef` still technically points at it. The `WeakRef` doesn't keep anything alive on its own.

  2. 02Why does every use of `weakRef.deref()` have to handle the case where it returns `undefined`?

    Because the object a `WeakRef` points at can be garbage collected at any point after nothing else references it, and that can happen between any two lines of your code. `.deref()` returns the live object if it still exists, or `undefined` if it's already gone — there's no way to know in advance which you'll get, so code that calls it has to treat the object as possibly-already-gone every single time.

  3. 03What's the difference between what `WeakRef` gives you and what `FinalizationRegistry` gives you?

    `WeakRef` lets you *hold* a non-owning reference to an object and check later whether it's still alive. `FinalizationRegistry` lets you *react* to an object being collected, by registering a callback the engine may run afterward. They're often used together — a `WeakRef` to check liveness on demand, a `FinalizationRegistry` entry to get notified passively — but neither one implies the other.

  4. 04Why is it wrong to rely on a `FinalizationRegistry` callback to close a database connection or release a lock that your program's correctness depends on?

    The callback's timing isn't guaranteed. The spec deliberately leaves exactly when — or even whether, before the process exits — a registered cleanup callback runs, because that depends on garbage collector internals the spec refuses to pin down. Anything that must happen reliably (closing a connection, releasing a lock) needs an explicit, deterministic cleanup path — a `close()` method you call yourself — with `FinalizationRegistry` treated as, at best, a backstop for cases where that explicit call got missed.

  5. 05What's the one kind of problem these two APIs are actually meant to solve, and why are they described as a last resort rather than a general memory-management tool?

    They exist for a cache or a side-table that needs to associate data with an object without that association itself keeping the object alive forever — e.g., caching an expensive computed value per object without leaking every object ever computed for. They're a last resort because almost every other memory concern already has a better, deterministic tool — explicit cleanup functions, `WeakMap` for keyed associations, scoping objects so they naturally fall out of use — and non-deterministic, GC-timing-dependent behavior is a bad foundation for anything you can avoid making GC-dependent in the first place.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark