JavaScript WeakRef

Beginner
7 min read
Updated: Nov 2026
3 examples
Memory

Definition and Usage

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.

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

Core Ideas

Ideas every WeakRef tutorial builds on:

IdeaExampleRemember
Createnew WeakRef(obj)Needs an object and the new keyword
Readref.deref()The object, or undefined
Methodsderef() onlyNo setter, no size, no way to re-point
Allowed targets{}, [], functionsStrings and numbers throw a TypeError
Check supporttypeof WeakRef === "function"Added in ES2021
Cleanup callbackFinalizationRegistryA separate tool, optional and never guaranteed

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.

QuestionNormal variableMap entryWeakRef
Keeps the object alive?YesYes, for keys and valuesNo
How do you read it?Use the variablemap.get(key)ref.deref()
Can the object vanish?No, while the variable existsNo, until you delete itYes, so deref() may give undefined
Good forEveryday dataLookups you controlOptional shortcuts, such as caches

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 the Right Tool

WeakRef is one of several memory-related tools. Pick the simplest one that fits:

You need toUse
Look things up by key, and you control the lifetimeMap
Attach data to an object without keeping it aliveWeakMap
Remember which objects you have seen, without keeping them aliveWeakSet
Hold one object loosely, for an optional cacheWeakRef
Run optional cleanup code after an object is collectedFinalizationRegistry

JavaScript Examples

Three short programs that show how strong references, weak references, and deref() fit together.

Example 1 — A Strong and a Weak Reference

One object, two ways to point at it. The normal variable is the object; the WeakRef is a separate wrapper you open with deref().

JavaScript
const book = { title: "JavaScript Basics" };
const strong = book;               // a normal (strong) reference
const weak = new WeakRef(book);    // a weak reference

console.log(strong === book);        // true
console.log(weak === book);          // false
console.log(weak.deref() === book);  // true
console.log(weak.deref().title);     // JavaScript Basics
deref() tutorial

How It Works

  1. Two names, one object. strong and book are the same object, so === is true. Both keep it in memory.
  2. A WeakRef is a wrapper. weak is a different object that merely points at the book, so comparing it with book gives false.
  3. Open it with deref(). weak.deref() returns the real book, so the title is readable. That works here because book still holds the object.

Example 2 — Which Values Can Be a Target

A WeakRef only accepts objects (and non-registered symbols). This helper tries several values and reports the error name instead of crashing.

JavaScript
function tryWeakRef(value) {
  try {
    new WeakRef(value);
    return "ok";
  } catch (e) {
    return e.name;
  }
}

console.log(tryWeakRef({}));                    // ok
console.log(tryWeakRef([1, 2, 3]));             // ok
console.log(tryWeakRef("text"));                // TypeError
console.log(tryWeakRef(42));                    // TypeError
console.log(tryWeakRef(Symbol.for("shared")));  // TypeError

How It Works

  1. Objects are fine. Plain objects, arrays, and functions are all objects, so new WeakRef() accepts them and the helper returns "ok".
  2. Primitives are refused. Strings and numbers are not objects, so the constructor throws a TypeError and the helper returns the error name.
  3. 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

How It Works

  1. Test before you use it. typeof WeakRef is "function" when the feature exists. It is safe to check even where WeakRef is not defined.
  2. 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.
  3. 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.

WeakRef Methods

WeakRef has only one method. It has a full tutorial with examples you can run in the browser.

MethodUse it to
deref()Get the target object, or undefined if it was collected

Constructor facts and what a WeakRef does not have: WeakRef Methods index.

Frequently Asked Questions

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.

Learn the deref() method

Read a weak reference safely, with three runnable examples you can edit.

deref() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

16 people found this page helpful