Skip to content
masterclassBuddyTech Buzz5 fresh blogs · 5:00 AM IST

JavaScript · Class

WeakRef

WeakRef provides a non-owning reference to an object or non-registered symbol, so the target may be garbage-collected. Use deref() to retrieve the target when it is still available; garbage-collection timing is nondeterministic.

Since
ES2021

How it works

WeakRef holds a non-owning reference to an object or non-registered symbol. Calling deref() retrieves the target while it remains available, or returns undefined after garbage collection; collection timing is nondeterministic.

Syntax

new WeakRef(target)

Parameters

NameTypeDescription
targetobject | symbolThe value to reference; it must be an object or a non-registered symbol.

Returns

A new WeakRef object referring to the supplied target; deref() returns the target or undefined if it has been reclaimed.

Key points

  • WeakRef observes a target without keeping it alive.
  • The target may be an object or a non-registered symbol.
  • The target can disappear when no strong references remain, but collection is optional.
  • deref() returns the target when available and undefined after reclamation.
  • The referenced value is called the target or referent.

Common mistakes

  • Do not use deref() as a deterministic signal that garbage collection has occurred.
  • A WeakRef cannot be retargeted after construction.

Example: Safely dereference a target

const target = {name: "Ada"};
const ref = new WeakRef(target);

const value = ref.deref();
if (value) {
  console.log(value.name);
}

Creates a weak reference and safely uses the target only when dereferencing still returns it.

When to use it

Memory-sensitive caches

Cache large objects without making the cache a strong owner of their memory.

Non-owning object tracking

Track optional objects such as DOM nodes without preventing their collection.

Ephemeral associations

Access a resource only while its target remains alive, with a fallback when deref() returns undefined.

  • WeakRef()
  • WeakRef.prototype.deref()
  • FinalizationRegistry
  • WeakMap
  • WeakSet

Source: WeakRef - JavaScript - MDN Web Docs. Checked 2026-10-15.