Sub topic 6
Why a deref()'d Target Survives the Current Job
This chapter assumes you already know how to create a WeakRef and call deref(), and that you understand the event loop at a conceptual level: tasks, microtasks, and the idea that synchronous code runs to completion. It explains one specific rule in the specification. Once your code has seen a weak target, that target cannot disappear in the middle of the code currently running.
The problem this rule solves
Modern engines run parts of garbage collection concurrently, on other threads, while your JavaScript executes. Suppose a collection could finish between any two lines of your code. Then this ordinary-looking snippet would be a race:
function describe(ref) {
if (ref.deref() !== undefined) {
// Could the target vanish right here?
return ref.deref().name;
}
return 'gone';
}
const ref = new WeakRef({ name: 'session' });
console.log(describe(ref));Without a guarantee, the first deref() could return the object and the second could return undefined, so .name would throw a TypeError. Every caller would need defensive code around each read, and bugs would show up only under particular memory pressure. That is the worst kind of bug to reproduce.
The specification prevents this. Within one synchronous run of JavaScript, the results of deref() are consistent. If a target was observed alive, it stays alive until that run finishes.
How the mechanism works internally
The specification gives each agent (roughly, each thread running JavaScript) a list called [[KeptAlive]]. Two operations add a target to that list through an abstract operation named AddToKeptAlive:
| Operation | Adds target to the kept-alive list? |
|---|---|
| `new WeakRef(target)` | Yes |
| `ref.deref()` when it returns the target | Yes |
| `ref.deref()` when it returns `undefined` | No (there is nothing to keep) |
| `registry.register(target, held)` | No |
| `weakMap.set(key, value)` | No |
The list holds its entries strongly. While an object is on it, the collector treats it as reachable, exactly as if a local variable pointed at it.
The host (the browser or Node.js) empties the list by calling ClearKeptObjects when a synchronous sequence of ECMAScript execution completes. The ECMAScript specification leaves the exact point to the host. The HTML specification, which browsers follow, calls ClearKeptObjects at the end of each microtask checkpoint, that is, after the current task and every microtask it queued have finished. Only after that can the collector reclaim the object, if nothing else references it.
Seeing the rule in action
You can watch this in Node.js by exposing the collector. The --expose-gc flag adds globalThis.gc(), which requests a full collection.
// Run with: node --expose-gc kept-alive.js
function makeRef() {
// The object is only reachable through the WeakRef.
return new WeakRef({ payload: new Array(1_000_000).fill(0) });
}
const ref = makeRef();
globalThis.gc();
console.log('same job, after gc():', ref.deref() !== undefined);
// Always true: the constructor put the target on the kept-alive list.
setTimeout(() => {
globalThis.gc();
console.log('later task, after gc():', ref.deref() !== undefined);
// Usually false: the list was cleared after the first job ended.
}, 0);The first line always prints true. You forced a full collection, and nothing in your code references the object, yet it survives. The new WeakRef(...) call in makeRef added it to the kept-alive list. The second line usually prints false. By the time the timer callback runs, the host has cleared the list, and gc() is free to reclaim the object. "Usually" matters here. The engine is never required to collect anything, so true is also a valid outcome.
Microtasks behave differently from timers. In hosts that clear the list at the end of the microtask checkpoint, a promise continuation still sees the target:
// Run with: node --expose-gc kept-alive-microtask.js
const ref = new WeakRef({ label: 'temporary' });
Promise.resolve().then(() => {
globalThis.gc();
console.log('in microtask:', ref.deref() !== undefined);
// true in current browsers and Node.js, but treat this as host behavior.
});What this means for everyday code
Repeated deref() calls are safe within one job
The describe function from the start of the chapter is correct. If the first deref() returns the object, the second one returns the same object. Even so, the clearer style is to read once and keep the result in a local variable:
function describe(ref) {
const target = ref.deref();
return target !== undefined ? target.name : 'gone';
}The local variable is an ordinary strong reference, so for this function it doesn't matter whether the kept-alive rule exists. The rule matters when the reads are spread across helper functions that each call deref() on their own.
await is a boundary
An await suspends the function. The rest of the function runs later as a microtask, possibly after other tasks. Treat every await as the end of the current job for reasoning purposes:
async function refresh(ref, fetchData) {
const before = ref.deref();
if (before === undefined) return;
const data = await fetchData();
// Do not assume ref.deref() still returns the object here.
// `before` is still valid because it is a strong local reference,
// which also means the object was never collectable during the await.
before.data = data;
}This example exposes a trade-off. Keeping before across the await keeps the object alive for the whole network call. If you want the object to be collectable while you wait, drop the local reference and call deref() again after the await, then handle undefined.
Creating a WeakRef never yields an immediately dead reference
Because the constructor adds the target to the list, new WeakRef(obj).deref() in the same job always returns obj. This matters for caches. A value you have just computed and wrapped will not vanish before you hand it back to the caller.
Edge cases and failure modes
Long synchronous loops accumulate kept objects
The kept-alive list is only cleared between jobs. A single long synchronous loop that creates many WeakRefs keeps every target alive until the loop finishes:
const refs = [];
for (let i = 0; i < 100_000; i++) {
refs.push(new WeakRef({ index: i, buffer: new Array(100).fill(i) }));
}
// Every target is still alive here, even though only WeakRefs point to them.
console.log(refs.every((r) => r.deref() !== undefined)); // trueIf you expected these objects to be reclaimed as the loop went, memory will peak higher than you planned. Breaking the work into chunks across tasks (for example with setTimeout or setImmediate) lets the host clear the list between chunks.
Tests that never yield cannot observe collection
A common mistake in tests is to create a WeakRef, force gc(), and check deref() in the same synchronous block. The check can never return undefined, so the test appears to "prove" that something leaks. A test that wants to see collection must yield to a later task first. Even then the result is a hint, because the engine may still keep the object.
FinalizationRegistry callbacks never interrupt your code
The same design idea applies to finalization. Cleanup callbacks are scheduled by the host as separate jobs. They never run in the middle of your synchronous code, so a deref() result cannot change underneath you because of a callback, and a callback cannot run while you are still using its target.
The rule only extends life; it never shortens it
Being on the kept-alive list is one more reason for an object to stay alive. Clearing the list does not make an object collectable if strong references from elsewhere still exist, and it never forces a collection. After clearing, the object becomes eligible, and that is all.
Summary
| Situation | Is the target guaranteed alive? |
|---|---|
| Same synchronous code, after `new WeakRef` or a successful `deref()` | Yes |
| Microtask queued by that code | Host-dependent (yes in browsers following HTML) |
| `setTimeout` callback or other later task | No |
| After an `await` | Do not assume so |
| Any point where you hold an ordinary variable to it | Yes |
Exercise
A function calls const a = ref.deref() and gets an object, then calls a helper that internally runs ref.deref().id in the same synchronous code. Can the helper throw because the target was collected? Explain which mechanism decides the answer.
Show answer
No. The first successful deref() added the target to the agent's [[KeptAlive]] list, which holds it strongly until the host calls ClearKeptObjects at the end of the current synchronous execution. The helper's deref() therefore returns the same object. The local variable a also holds it strongly, so the object is alive for two separate reasons.
Exercise
A test creates const ref = new WeakRef({}), calls globalThis.gc() on the next line, and asserts that ref.deref() is undefined. The assertion always fails. Why, and how would you restructure the test?
Show answer
The WeakRef constructor put the target on the kept-alive list, and the list is not cleared until the current job ends, so gc() in the same job cannot collect it. Move the gc() call and the check into a later task, for example inside setTimeout(..., 0). Even then, accept that collection is not guaranteed and treat a surviving object as an inconclusive result, not a failure.
Exercise
A synchronous loop creates 500,000 WeakRefs to freshly allocated objects and keeps only the WeakRefs. Memory peaks far higher than expected. What causes this, and what change reduces the peak?
Show answer
Each new WeakRef call adds its target to the kept-alive list, and the list is only cleared between jobs, so all 500,000 targets stay alive until the loop finishes. Splitting the loop into chunks scheduled as separate tasks, such as with setTimeout or setImmediate, lets the host clear the list between chunks, so the collector can reclaim earlier targets.