In JavaScript, a WeakRef is a small object that points to another object without keeping it alive. You create one with new WeakRef(target). Later you call ref.deref() to get the target back. If the garbage collector has already removed the target, deref() returns undefined.
Normally, while any part of your code still points to an object, JavaScript keeps it in memory. That is a strong reference. A WeakRef is a weak reference: it does not count. When only weak references are left, the engine may remove the object, and it decides when.
WeakRef arrived in ES2021 and has just one method, deref(). Most programs never need it. It helps with a few special jobs, such as an optional cache. The WeakRef Methods index lists the guide.
Weak means “may be gone”.
Always check the result of deref() for undefined, and never write code that needs garbage collection to happen.
Syntax
JavaScript Syntax
Create a WeakRef with new, then read the target with deref():
JavaScript
const target = { name: "Asha" };
const ref = new WeakRef(target); // weak reference to target
const obj = ref.deref(); // target, or undefined
const name = ref.deref()?.name; // safe property read
typeof WeakRef === "function"; // feature check
Reference
Core Ideas
Ideas every WeakRef tutorial builds on:
Idea
Example
Remember
Create
new WeakRef(obj)
Needs an object and the new keyword
Read
ref.deref()
The object, or undefined
Methods
deref() only
No setter, no size, no way to re-point
Allowed targets
{}, [], functions
Strings and numbers throw a TypeError
Check support
typeof WeakRef === "function"
Added in ES2021
Cleanup callback
FinalizationRegistry
A separate tool, optional and never guaranteed
Compare
Strong vs Weak References
A strong reference is anything that holds an object: a variable, a property, an array item, a Map entry. A weak reference points to an object but does not hold it.
Question
Normal variable
Map entry
WeakRef
Keeps the object alive?
Yes
Yes, for keys and values
No
How do you read it?
Use the variable
map.get(key)
ref.deref()
Can the object vanish?
No, while the variable exists
No, until you delete it
Yes, so deref() may give undefined
Good for
Everyday data
Lookups you control
Optional shortcuts, such as caches
Important
Garbage Collection Is Not Predictable
JavaScript frees memory for you. An object with no strong references can be removed, but the language does not say when. It can differ between browsers, versions, and runs, and sometimes it never happens before the page closes. That gives you two simple rules.
Rule 1: always handle undefined from deref(). Rule 2: your program must stay correct whether the object is there or not. If you need exact timing, use something else, such as a normal Map with a size limit.
One helpful detail: once deref() has returned an object, that object stays alive until the current synchronous run of code ends. So inside one function you can call deref() again and get the same object. Only after the code finishes and the event loop moves on can it be removed.
Choose
Choose the Right Tool
WeakRef is one of several memory-related tools. Pick the simplest one that fits:
You need to
Use
Look things up by key, and you control the lifetime
Map
Attach data to an object without keeping it alive
WeakMap
Remember which objects you have seen, without keeping them alive
WeakSet
Hold one object loosely, for an optional cache
WeakRef
Run optional cleanup code after an object is collected
Objects are fine. Plain objects, arrays, and functions are all objects, so new WeakRef() accepts them and the helper returns "ok".
Primitives are refused. Strings and numbers are not objects, so the constructor throws a TypeError and the helper returns the error name.
Registered symbols too.Symbol.for("shared") is kept in a global registry that anyone can look up, so it is rejected. A symbol from Symbol("x") is allowed.
Example 3 — Check That WeakRef Exists
Very old browsers have no WeakRef. This helper tests for it first and falls back to a normal reference, so the rest of your code works either way.
JavaScript
function makeRef(obj) {
if (typeof WeakRef === "function") {
return new WeakRef(obj);
}
return { deref: function () { return obj; } };
}
const config = { mode: "fast" };
const ref = makeRef(config);
console.log(typeof WeakRef); // function
console.log(ref.deref() === config); // true
console.log(ref.deref().mode); // fast
Test before you use it.typeof WeakRef is "function" when the feature exists. It is safe to check even where WeakRef is not defined.
Same shape, two backends. The fallback object also has a deref() method, so the calling code does not need to know which kind of reference it received.
The fallback is strong. It keeps obj in memory for good. That is fine for a fallback, because the code still works; it just never frees that memory early.
Continue
WeakRef Methods
WeakRef has only one method. It has a full tutorial with examples you can run in the browser.
A WeakRef is an object that points to another object without keeping it in memory. You create one with new WeakRef(target) and read the target later with ref.deref(), which returns the object or undefined if it has been garbage collected.
A normal variable, property, or Map entry is a strong reference: while it exists, the garbage collector will not remove the object. A weak reference does not count, so when only weak references remain, the engine is free to remove the object whenever it likes.
No. Garbage collection timing is up to the engine and is never guaranteed. An object may stay for a long time, or go sooner than you expect. Write code that is correct whether deref() returns the object or undefined.
Objects, which includes arrays and functions, and symbols that are not registered with Symbol.for(). Numbers, strings, booleans, null, and undefined throw a TypeError. Calling WeakRef without new also throws a TypeError.
Most programs need none of them. A WeakMap or WeakSet attaches data to objects without keeping them alive. A WeakRef lets you hold one object loosely for an optional cache. A normal Map is simplest and predictable. Pair WeakRef with a FinalizationRegistry only for optional cleanup.