JavaScript WeakRef and Nondeterministic Finalization
Quick answer
WeakRef provides optional access to a weakly held target. FinalizationRegistry can request a cleanup callback after a target is reclaimed, but neither gives deterministic collection timing.
How it works
new WeakRef(target) creates a weak reference; deref() returns the target if still available or undefined. Use the result as a strong local variable while working. FinalizationRegistry(callback) registers a target, a held value and optional unregister token. Held values must not keep the target alive through a reference chain. Cleanup may be delayed or never happen before exit. Use explicit cleanup for correctness; never assert GC timing.
const obj={name:"item"}; const ref=new WeakRef(obj); console.log(ref.deref()===obj);Expected output in Node.js:
trueThe target is strongly held and accessed synchronously.
const target={}; const token={}; const r=new FinalizationRegistry(()=>{}); r.register(target,"label",token); console.log(r.unregister(token),r.unregister(token));Expected output in Node.js:
true falseThe first call removes the registration; no GC event is required.
Common mistakes
Never use finalization as the only mechanism for closing files, saving data or releasing critical resources.
Practice
Design a cache whose missing weak target can be rebuilt; describe an explicit disposal path for resources.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
JavaScript WeakRef and Nondeterministic Finalization — Knowledge Check
Apply the taught concept and predict the output.
What may WeakRef.deref return after reclamation?
When is a finalization callback guaranteed to execute?
How should a critical resource be released?
What is the exact console output in JavaScript WeakRef and Nondeterministic Finalization example 1?
const obj={name:"item"}; const ref=new WeakRef(obj); console.log(ref.deref()===obj);What is the exact console output in JavaScript WeakRef and Nondeterministic Finalization example 2?
const target={}; const token={}; const r=new FinalizationRegistry(()=>{}); r.register(target,"label",token); console.log(r.unregister(token),r.unregister(token));