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, tasks, and microtasks at a conceptual level. It covers one rule that makes deref() safe to use: a target you have just observed cannot disappear in the middle of your synchronous code.
The problem the rule solves
Without this rule, the garbage collector could run between any two statements. Code like this would then be unreliable:
const ref = new WeakRef({ count: 1 });
if (ref.deref() !== undefined) {
// Could the object vanish right here?
console.log(ref.deref().count);
}If collection could happen between the two deref() calls, the second one might return undefined and throw a TypeError. Your program's behavior would then depend on when the collector happened to run, which you cannot control.
The kept-alive list
The ECMAScript specification avoids this with an internal list of "kept-alive" objects. An object is added to that list in two situations:
- A
WeakRefis constructed with it as the target. - A call to
deref()returns it.
While an object is on the list, the engine treats it as strongly held. The host (the browser or Node.js) empties the list when the current synchronous run of JavaScript finishes. The specification calls this operation ClearKeptObjects. In browsers it runs at the end of a microtask checkpoint, after the microtask queue has been drained.
So within one job, every deref() on the same WeakRef returns the same result. Once you have seen the object, it stays alive until that job ends.
Crossing a job boundary
The guarantee stops at the job boundary. An await, a setTimeout callback, or an event handler can each run after the list has been cleared. Any result you got from deref() before that point tells you nothing about what a later call will return.
async function report(ref) {
const before = ref.deref();
console.log('before await:', before !== undefined);
await new Promise((resolve) => setTimeout(resolve, 100));
// A new job: the earlier guarantee has expired.
const after = ref.deref();
if (after === undefined) {
console.log('collected while we waited');
} else {
console.log('still alive:', after.label);
}
}
report(new WeakRef({ label: 'temp' }));In this example, before is a local variable that strongly references the object until report returns. That strong reference keeps the object alive across the await. The kept-alive list does not. If you want the object to stay collectable, don't hold the deref() result across an await. Call deref() again after the await and check the new result.
Common errors
| Mistake | Consequence |
|---|---|
| Expecting a target to be collected in the same job it was created or dereferenced | It never is; the kept-alive list prevents it |
| Holding a `deref()` result in a variable across `await` | The variable is a strong reference, so the object stays alive |
| Assuming one `deref()` check covers later callbacks | A later job may get `undefined` |
Exercise
You create const ref = new WeakRef({}) and call globalThis.gc() on the very next line in Node.js with --expose-gc. Will ref.deref() on the line after that return undefined?
Show answer
No. Constructing the WeakRef added its target to the kept-alive list, so the target cannot be collected until the current job ends. Within that job, deref() still returns the object.
Exercise
Inside an async function you call ref.deref() before an await and do not save the result. After the await, is the target guaranteed to still exist?
Show answer
No. The await resumes in a later job, and the kept-alive list was cleared before that job started. You must call deref() again and check for undefined.