JavaScript Reference ยท Collections
WeakRef and FinalizationRegistry
Reference for WeakRef and FinalizationRegistry in JavaScript: hold an object weakly, read it with deref(), register cleanup callbacks, and know the caveats.
A WeakRef holds a reference to an object without keeping it alive. Call deref() to get the object back, or undefined if the garbage collector has already removed it. A FinalizationRegistry lets you ask for a callback after a registered object has been collected, typically to clean up something outside of JavaScript's memory.
Both are low-level tools. Garbage collection timing is up to the engine, so correct programs must never depend on an object being collected, or on a callback running. Prefer a plain WeakMap or WeakSet when they are enough.
const ref = new WeakRef({ big: "data" }); const target = ref.deref(); // the object, or undefined if collected
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
new WeakRef(target) weakRef.deref() new FinalizationRegistry(callback) registry.register(target, heldValue) registry.register(target, heldValue, unregisterToken) registry.unregister(unregisterToken)
| Name | Description |
|---|---|
target |
The object (or non-registered symbol) to refer to weakly. |
callback |
Called with heldValue after the target has been collected. |
heldValue |
Any value passed to the callback. It must not be the target itself, and it should not refer to it, because that would keep the target alive. |
unregisterToken |
Optional object used to cancel registrations later. It is held weakly. |
Return value: deref() returns the target or undefined. register() returns undefined. unregister() returns true if at least one registration was removed.
Exceptions: new WeakRef() and register() throw a TypeError if the target is not an object or non-registered symbol, and register() throws if heldValue is the same as the target.
Usage notes
- Stable within one task. If
deref()returns an object, repeated calls in the same synchronous run keep returning it, so you can rely on it until you yield to the event loop. - Store the result. Call
deref()once, keep the result in a variable, and test it forundefined. - Callbacks are not guaranteed. The page may close first, or the engine may never collect the object. Never use the callback for logic that must happen.
- Cleanup only. Typical uses are releasing external resources, such as handles in WebAssembly, or pruning a cache's map of stale keys.
- Hard to test. Collection cannot be triggered from standard JavaScript, so examples cannot show a collection happening.
- Prefer simpler designs. Explicit
close()ordispose()methods are more predictable than finalizers.
Browser support
Both are supported by current browsers and Node.js. Check a compatibility table if you target very old environments.
Related
- WeakMap, WeakSet
- Lesson: WeakMap, WeakSet and WeakRef