JavaScript WeakRef Methods

About This Index
This page is the JavaScript WeakRef Methods index for the tutorial track. A WeakRef has just one method, so there is one guide, with syntax, three runnable examples, browser notes, and FAQs.
Learn what a weak reference is on /js/weakref. Use this page when you want the API: deref() and the constructor facts below.
Always check the result of deref(). It is the object while the object is alive and undefined after it has been garbage collected.
How to Use a WeakRef
Create the WeakRef with new, then call its one method with a dot:
const user = { name: "Asha" };
const ref = new WeakRef(user); // weak: does not keep user alive
ref.deref(); // the object, or undefined
ref.deref()?.name; // safe property read
const obj = ref.deref(); // strong again while obj exists
if (obj !== undefined) {
// use obj here
} JavaScript WeakRef Methods Table
The method guide in this JavaScript tutorial series (1 tutorial), grouped by what it does.
Read the target
1 methodThe only method on a WeakRef. It returns the object the WeakRef points to, or undefined once the garbage collector has removed it (ES2021).
WeakRef Constructor and Facts
The constructor is used with new. The last row lists things a WeakRef does not have.
| Member | What it gives you | Since |
|---|---|---|
new WeakRef(target) | Create a weak reference to an object. Call it with new; without it you get a TypeError. | ES2021 |
new WeakRef(symbol) | A symbol from Symbol("x") also works as the target. A symbol from Symbol.for("x") does not. | ES2023 |
ref.deref() | Return the target, or undefined if it was garbage collected. This is the only method. | ES2021 |
Object.prototype.toString.call(ref) | Gives "[object WeakRef]", because every WeakRef is tagged with Symbol.toStringTag. | ES2021 |
ref.size, ref.target, ref.set() | None of these exist. A WeakRef has no other members, and you cannot point it at a new target. Create a new WeakRef instead. | - |
Frequently Asked Questions
Start with WeakRef deref()
Learn how to read a weak reference safely, with three runnable examples.
14 people found this page helpful
