Skip to content
Tutorials Center
My learning

Topics

Lesson 57 of 156 ยท Arrays

WeakMap, WeakSet and WeakRef

Learn how weak references work in JavaScript - WeakMap for private data and caches, WeakSet for tagging objects, and WeakRef and FinalizationRegistry with care.

A normal Map or Set holds on to everything you put in it. As long as the collection exists, its keys and values stay in memory, even if no other part of your program uses them anymore. Usually that's exactly what you want. But sometimes you want to attach information to an object only for as long as that object lives, and let it vanish automatically when the object is gone.

That's what weak collections are for. A WeakMap or WeakSet refers to its objects weakly: the reference doesn't count when the garbage collector decides what to keep. This lesson explains what that means, shows the patterns where weak collections shine (private data, caches, marking objects), and then covers the two lower-level tools, WeakRef and FinalizationRegistry, along with the honest warnings that come with them.

Strong and weak references

JavaScript manages memory for you. The engine's garbage collector periodically finds objects that can no longer be reached from your code (no variable, property or closure leads to them) and frees their memory.

A normal reference is strong: as long as it exists, the object it points to is reachable and must stay alive. Collections hold strong references:

JavaScript
let user = { name: "Kai" };
const visits = new Map();
visits.set(user, 3);

user = null;
// The object { name: "Kai" } can't be collected:
// the Map still holds it as a key. visits.size is still 1.

A weak reference is different. It lets you reach the object while it exists, but it doesn't keep it alive. If the only remaining references to an object are weak ones, the garbage collector is free to remove it, and the weak entry disappears with it.

WeakMap

A WeakMap is a map whose keys are held weakly. Keys must be objects (or symbols that weren't created with Symbol.for()); the values can be anything. The API is deliberately small:

Method What it does
set(key, value) Adds or updates an entry; returns the WeakMap
get(key) Returns the value, or undefined
has(key) true if the key has an entry
delete(key) Removes the entry; returns true if it existed

There is no size, no clear(), no keys() and no forEach. A WeakMap can't be looped over at all. That's not an oversight: entries can disappear at any moment when the garbage collector runs, so a count or a list would be unpredictable. Without iteration, your code can never observe when collection happens.

JS WeakMap basics

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Keys are matched by identity, just like in a Map: { id: 1 } looks the same as article but is a different object, so it has no entry.

Pattern: attaching data to objects you don't own

The classic use for a WeakMap is to store extra information about objects without changing them: DOM elements, objects from a library, or objects passed in by other code. Adding a property would pollute the object (and could clash with other code). Storing the data in a normal Map would keep every object alive forever. A WeakMap gives you a side table that cleans itself up.

Per-element data with a WeakMap

When a button is removed from the page and no other code refers to it, both the element and its click data become collectible. You don't have to write any cleanup code. (In this demo the first variable and the event listener's closure hold references for a while, which is fine: collection happens whenever the element is truly unreachable.)

Pattern: private data

Before classes had private fields, a WeakMap was the standard way to give objects truly hidden data. The WeakMap lives in a module or closure, and each instance is a key:

JavaScript
const secrets = new WeakMap();

class Account {
  constructor(owner, pin) {
    this.owner = owner;
    secrets.set(this, { pin, attempts: 0 });
  }

  unlock(pin) {
    const data = secrets.get(this);
    data.attempts++;
    return pin === data.pin;
  }
}

Code outside can't reach secrets, so the PIN is invisible: it doesn't show in Object.keys(), JSON.stringify() or the console. When an Account is garbage collected, its secret entry goes too. Today, #pin fields do this job with less ceremony, but you'll still meet the WeakMap pattern in libraries and older code, and it remains useful when you need private data for objects created by someone else.

Pattern: caching results per object

A cache keyed by object is another natural fit. If you compute something expensive from an object, a WeakMap remembers the result while the object lives, and drops it when the object is gone, with no growing memory and no manual invalidation.

JS A per-object cache

Press Run (or Ctrl + Enter) to see the console output here.

No output.

This only stays correct if you treat the cached objects as immutable. If someone pushes a new score into scores, the cache still returns the old stats. That's why per-object caches pair so well with the immutable update style: a change creates a new array, which naturally gets a fresh cache entry.

WeakSet

A WeakSet is a set of objects held weakly. It has just add(), has() and delete(), with no size and no iteration. Use it to mark objects: "I've seen this one", "this one is already processed", "this one is valid".

JS Marking objects with a WeakSet

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The cycle detector shows a handy trick: a WeakSet passed through a recursive walk remembers visited objects, so self-references don't cause infinite loops. A normal Set would work here too; the weak one simply guarantees it never holds anything longer than needed.

WeakRef: a weak pointer to one object

WeakRef (ES2021) is a lower-level tool: a single weak reference to one object. You create it with new WeakRef(target) and get the object back with deref(), which returns the object, or undefined if it has already been collected.

JavaScript
const bigImageData = { pixels: new Uint8Array(10_000_000) };
const ref = new WeakRef(bigImageData);

// Later...
const data = ref.deref();
if (data) {
  // still in memory: use it
} else {
  // it was collected: rebuild or reload it
}

The usual use case is a cache of large, re-creatable objects that you'd like to keep around if memory allows, but that the engine may reclaim under pressure.

FinalizationRegistry: hearing about collection

A FinalizationRegistry lets you register a callback that may run some time after an object has been garbage collected:

JavaScript
const registry = new FinalizationRegistry((heldValue) => {
  console.log(`Object for ${heldValue} was collected`);
});

let session = { user: "kai" };
registry.register(session, "kai's session"); // the held value is passed to the callback
session = null;
// At some unknown later point, the callback *might* run.

The held value must not be the object itself (that would keep it alive). It's typically a string, id or small handle used to clean up something outside the object, such as a cache entry pointing at a collected WeakRef.

Avoid WeakRef and FinalizationRegistry unless you really need them. Garbage collection timing is up to the engine and differs between browsers, versions and even runs. An object may live much longer than you expect, or be collected sooner. Finalization callbacks may run late or never (for example, when the tab closes). Never use them for essential logic like saving data or releasing important resources: use explicit methods like close() or dispose() for that. Treat them as optional, best-effort memory optimizations.

This is also why there's no live demo of collection here: you can't force garbage collection from normal JavaScript, so a demo couldn't reliably show an entry disappearing. If you want to watch it happen, your browser's DevTools memory panel has a button to trigger collection manually.

Choosing the right collection

You need to... Use
Store key-value data and loop over it Map
Store unique values and count or list them Set
Attach data to objects without keeping them alive WeakMap
Mark objects as seen/processed without keeping them alive WeakSet
Keep a large re-creatable object only while memory allows WeakRef (rarely)
Run optional cleanup after collection FinalizationRegistry (very rarely)

Rule of thumb: if you need iteration or size, you need a regular collection. If the keys are objects whose lifetime someone else controls, reach for a weak one.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why doesn't WeakMap have a size property or iteration?

    Hiding size and iteration means your code can never observe when collection happens, which keeps programs predictable.
  2. 2. Which call throws a TypeError?

    WeakMap keys must be objects or non-registered symbols. Using a string as a key in set() throws; get() with a string just returns undefined.
  3. 3. What does ref.deref() return after the target object has been garbage collected?

    deref() returns the target while it's alive and undefined once it has been collected, so always check the result.
  4. 4. Which is a good job for a FinalizationRegistry?

    Finalization callbacks may run late or never, so they suit best-effort cleanup only, never essential work.
  5. 5. You attach metadata to DOM elements that other code may remove. Which collection avoids memory leaks?

    A WeakMap doesn't keep the removed elements alive, so their entries can be collected together with them.

Summary

  • Weak references don't keep objects alive; when only weak references remain, the garbage collector may remove the object.
  • WeakMap holds object keys weakly; it has set, get, has and delete, but no size or iteration.
  • Use WeakMaps for data attached to objects you don't own, private data and per-object caches.
  • WeakSet marks objects as seen or processed, and helps detect cycles.
  • WeakRef and FinalizationRegistry expose garbage collection directly; their timing is unpredictable, so use them only for optional optimizations.

Next: Prototypes โ€” how JavaScript objects share behavior through the prototype chain.