Sub topic 4
Creating a WeakRef and Calling deref()
This chapter assumes you know how JavaScript objects and references work, that you are comfortable with closures, and that you have a rough picture of the event loop. It also builds on the previous chapters on reachability and on strong and weak references. Here you will learn the API itself: how to construct a WeakRef, how to read its target with deref(), and the coding habits that keep that read safe.
The Whole API in Two Members
A WeakRef is an object that holds a weak reference to one other value, called its target. The garbage collector ignores the weak reference when it decides whether the target is reachable. The API has two parts:
| Member | What it does |
|---|---|
| `new WeakRef(target)` | Creates a weak reference to `target`. The target is fixed for the life of the `WeakRef`. |
| `ref.deref()` | Returns the target if it is still alive, or `undefined` if it has been collected. |
There is no setter, no "is alive" property, and no event that fires when the target disappears. deref() is the only way to look at the target, and it tells you only what is true right now.
Constructing a WeakRef
You must call the constructor with new. The argument must be a value that can be held weakly, which in practice usually means an object. The chapter "What Can Be a Weak Target" covers the full rules, including symbols.
let target = { name: 'large object' };
const ref = new WeakRef(target);
console.log(ref.deref() === target); // true: same object, not a copy
console.log(Object.prototype.toString.call(ref)); // "[object WeakRef]"
try {
WeakRef(target); // forgot `new`
} catch (err) {
console.log(err instanceof TypeError); // true
}
try {
new WeakRef(42); // primitives cannot be weak targets
} catch (err) {
console.log(err instanceof TypeError); // true
}The WeakRef does not copy, wrap, or proxy the target. deref() returns the original object, so identity checks with === work as expected.
Each call to the constructor creates a separate WeakRef, even for the same target:
const shared = {};
const a = new WeakRef(shared);
const b = new WeakRef(shared);
console.log(a === b); // false: two distinct WeakRef objects
console.log(a.deref() === b.deref()); // true: same targetThat means you cannot use a WeakRef as a stand-in for its target's identity. If you need to look something up by its target, use a WeakMap keyed by the target itself.
The WeakRef itself is a normal object
The reference inside a WeakRef is weak, but the WeakRef object is held like any other object. If you put a thousand WeakRefs in an array, the array keeps all thousand wrappers alive, even after every target has been collected. That small leftover object is the reason the weak-value cache pattern later in this tutorial needs a cleanup step.
Reading the Target Safely
deref() can return undefined at any point after the last strong reference to the target goes away. The correct pattern is: call deref() once, store the result in a local variable, check it, then use the local variable.
let target = { name: 'large object' };
const ref = new WeakRef(target);
const obj = ref.deref();
if (obj !== undefined) {
console.log(obj.name);
} else {
console.log('Target was garbage collected');
}
target = null; // the WeakRef alone does not keep the object aliveThe local variable obj is a strong reference. While it is in scope and in use, the target cannot be collected. So every line inside the if block sees a live object.
Two facts from the diagram matter when you write code.
- Collection is one-way. Once
deref()returnsundefined, it returnsundefinedforever. A target never comes back. - "Weakly reachable" is not "collected". Dropping the last strong reference does not cause
deref()to returnundefinedat once. The object stays readable until the collector actually runs and decides to reclaim it, which may be milliseconds later, minutes later, or never.
Why you must not call deref() twice
This version looks harmless but has a bug:
function logName(ref) {
if (ref.deref() !== undefined) {
console.log(ref.deref().name); // second call
}
}
logName(new WeakRef({ name: 'temp' }));Inside one synchronous run of code this happens to work, because the engine keeps a deref()'d target alive until the current job ends. The chapter "Why a deref()'d Target Survives the Current Job" explains that rule in detail. The habit still breaks as soon as there is an await between the check and the use:
async function logNameLater(ref) {
if (ref.deref() !== undefined) {
await new Promise((resolve) => setTimeout(resolve, 1000));
console.log(ref.deref().name); // may throw: Cannot read properties of undefined
}
}
logNameLater(new WeakRef({ name: 'temp' }));After the await, the code runs in a new job, and the target may have been collected in between. The fix is the single-read pattern: read once into a local, and that local keeps the object alive across the await.
async function logNameLaterFixed(ref) {
const obj = ref.deref();
if (obj === undefined) return;
await new Promise((resolve) => setTimeout(resolve, 1000));
console.log(obj.name); // safe: `obj` is a strong reference
}
logNameLaterFixed(new WeakRef({ name: 'temp' }));A Worked Example: A Ticker That Stops When Its Subscriber Disappears
A common reason to reach for WeakRef is a long-lived producer, such as a timer, that should not keep its consumers alive. A closure that captures the consumer directly would hold it strongly forever. A WeakRef lets the timer notice when the consumer is gone and shut itself down.
function startTicker(subscriber, intervalMs) {
const ref = new WeakRef(subscriber);
// Do not use `subscriber` below this line: the closure would hold it strongly.
const id = setInterval(() => {
const sub = ref.deref();
if (sub === undefined) {
clearInterval(id);
console.log('Subscriber collected; ticker stopped');
return;
}
sub.onTick(Date.now());
}, intervalMs);
return id;
}
let widget = {
ticks: 0,
onTick(time) {
this.ticks += 1;
console.log(`tick ${this.ticks} at ${time}`);
},
};
startTicker(widget, 500);
setTimeout(() => {
widget = null; // the ticker will stop once the GC reclaims the widget
console.log('Widget released');
}, 2000);Run this in Node.js and you will see a few ticks, then "Widget released", and then possibly more ticks. The ticks continue until the collector actually reclaims the widget. In a small script with little memory pressure, that may never happen and the process will tick forever. That is correct behavior, not a bug in your code. The chapter on observing GC behavior shows how to force a collection with --expose-gc when you want to watch this happen.
Note the comment inside startTicker. The parameter subscriber is still in the function's scope, so if the interval callback mentioned it even once, the closure would capture it strongly and the WeakRef would do nothing. This is the most common way a WeakRef silently stops being weak.
Feature Detection
WeakRef shipped in ES2021 and is available in all current browsers and in Node.js 14.6 and later. If you need to support older runtimes, check for it and fall back to a strong reference:
function makeRef(obj) {
if (typeof WeakRef === 'function') {
return new WeakRef(obj);
}
return { deref: () => obj }; // strong fallback: never collected
}
const r = makeRef({ id: 1 });
console.log(r.deref().id); // 1The fallback still behaves correctly, because a target that is never collected is a legal outcome for a real WeakRef too. Your code must already handle both cases.
Common Errors
| Mistake | Symptom | Fix |
|---|---|---|
| Calling `WeakRef(obj)` without `new` | `TypeError` | Always use `new WeakRef(obj)` |
| Calling `deref()` again after an `await` | Intermittent `Cannot read properties of undefined` | Read once into a local before the `await` |
| A closure also captures the target directly | Target is never collected | Reference only the `WeakRef` inside long-lived closures |
| Storing `deref()`'s result in a field or global | Target is never collected | Keep the result in a short-lived local |
| Expecting `undefined` right after `obj = null` | Test "fails" because the object is still there | Treat collection timing as unknown |
| Comparing two `WeakRef`s with `===` | Always `false` for separate wrappers | Compare `a.deref() === b.deref()` or key a `WeakMap` by the target |
Exercise
A colleague writes if (ref.deref()) { await save(); ref.deref().markSaved(); }. Explain the two problems with this code and rewrite it correctly.
Show answer
First, ref.deref() is called twice with an await in between. The target can be collected while save() is pending, so the second deref() may return undefined and the call to markSaved() throws. Second, the truthiness check is looser than it needs to be. deref() returns either an object or undefined, so !== undefined states the intent exactly. Corrected: const obj = ref.deref(); if (obj !== undefined) { await save(); obj.markSaved(); }. The local obj keeps the target alive across the await.
Exercise
In the ticker example, suppose the interval callback is changed to const sub = ref.deref() ?? subscriber;. What happens to the widget after widget = null, and why?
Show answer
The widget is never collected and the ticker never stops. The callback now refers to the subscriber parameter, so the closure captures a strong reference to the widget. That reference lives as long as the interval does, and the interval lives until the widget is collected. Each one keeps the other alive, and the WeakRef has no effect.
Exercise
You set target = null, and the next line logs ref.deref(). It prints the object, not undefined. Is the engine broken?
Show answer
No. Dropping the last strong reference only makes the target eligible for collection. The garbage collector decides when, or whether, to reclaim it. Also, the engine keeps a deref()'d target alive until the end of the current job, so within the same synchronous run you will keep seeing it either way. deref() returns undefined only after an actual collection.