WeakMap, WeakSet, WeakRef and FinalizationRegistry: Memory-Friendly References in JavaScript
How garbage collection decides what to free, why a Map used as a cache can leak memory, and how WeakMap and WeakSet attach data to objects without keeping them alive. Plus WeakRef and FinalizationRegistry, symbols as weak keys, and when (rarely) to use them.
kvi5hnuCode Sprout team member7 min readOn this page
JavaScript frees memory automatically, but only for objects your program can no longer reach. A Map or Set that holds an object keeps it reachable forever, even after the rest of your program has forgotten it. Weak collections solve this: they hold their keys without keeping them alive. This article explains the problem and the four "weak" tools: WeakMap, WeakSet, WeakRef and FinalizationRegistry.
Garbage collection in one paragraph
The JavaScript engine's garbage collector (GC) periodically finds objects that are unreachable: no variable, property, closure or collection that the running program can access refers to them, directly or through other objects. Those objects can never be used again, so their memory is reclaimed. You never free memory yourself. You can only make objects unreachable by dropping your references to them (letting variables go out of scope, removing them from arrays, setting properties to null).
The catch: a reference from a collection counts. If a Map holds an object as a key, that object stays reachable for as long as the map does.
The leak: caching data about objects in a Map
Suppose you compute something expensive about objects and cache the results:
const layoutCache = new Map();
function measure(element) {
if (!layoutCache.has(element)) {
layoutCache.set(element, { width: element.text.length * 8 }); // "expensive"
}
return layoutCache.get(element);
}
let card = { text: "Hello" };
console.log(measure(card).width);
card = null; // we're done with the card...
console.log(layoutCache.size); // ...but the cache still holds it
40
1
Every element ever measured stays in memory with its cached data, even after it's removed from the page. In a long-running app, that's a memory leak.
WeakMap
A WeakMap holds its keys weakly: an entry doesn't keep its key object alive. When nothing else references the key, the GC can free the object, and the entry (with its value) disappears too.

const layoutCache = new WeakMap();
function measure(element) {
if (!layoutCache.has(element)) {
layoutCache.set(element, { width: element.text.length * 8 });
}
return layoutCache.get(element);
}
let card = { text: "Hello" };
console.log(measure(card).width, layoutCache.has(card));
card = null; // now the card and its cache entry can be collected
40 true
The API is a subset of Map's:
set(key, value),get(key),has(key),delete(key), and (ES2026)getOrInsert/getOrInsertComputed.- Keys must be objects (or non-registered symbols, below); primitives throw a
TypeError. - No
size, no iteration, nokeys(), noclear(). The engine decides when to collect objects, so the contents could change at any moment; exposing them would make your program depend on GC timing.
const wm = new WeakMap();
const key = {};
wm.set(key, "data");
console.log(wm.get(key), wm.size, typeof wm.keys);
try {
wm.set("name", "Ana");
} catch (err) {
console.log(err.name, err.message);
}
data undefined undefined
TypeError Invalid value used as weak map key
What WeakMaps are used for
- Caching computed data about objects you don't own (DOM nodes, request objects, parsed files), as above.
- Attaching metadata to objects without modifying them: event listeners per element, "last seen" timestamps per user object, framework bookkeeping. Vue's reactivity system, for example, keeps its per-object dependency data in a WeakMap.
- Private data for objects, the pre-
#privatetechnique:
const secrets = new WeakMap();
class Account {
constructor(owner, pin) {
this.owner = owner;
secrets.set(this, { pin }); // stored outside the object
}
checkPin(pin) {
return secrets.get(this).pin === pin;
}
}
const acct = new Account("Ana", "4321");
console.log(acct.checkPin("0000"), acct.checkPin("4321"), Object.keys(acct));
false true [ 'owner' ]
When an Account is no longer referenced, its secret entry goes away with it. Today #pin fields (article 71) do this more simply, but you'll see the WeakMap pattern in older code and transpiler output.
WeakSet
A WeakSet is the weak version of Set: a group of objects with add, has and delete, no size and no iteration. It answers one question, "have I seen or marked this object?", without keeping objects alive:
const processed = new WeakSet();
function processOnce(order) {
if (processed.has(order)) return "already processed";
processed.add(order);
return `processed order ${order.id}`;
}
const order = { id: 7 };
console.log(processOnce(order));
console.log(processOnce(order));
console.log(processOnce({ id: 7 })); // a different object
processed order 7
already processed
processed order 7
Other uses: detecting cycles while walking an object graph (record each visited object), or "branding" objects created by a trusted factory.
Symbols as weak keys
Since ES2023, WeakMap keys, WeakSet members and WeakRef targets can also be symbols created with Symbol(). Symbols from Symbol.for() can't be used, because they're registered globally and never collected:
const wm = new WeakMap();
const token = Symbol("session");
wm.set(token, { user: "Ana" });
console.log(wm.get(token).user);
try {
wm.set(Symbol.for("shared"), 1);
} catch (err) {
console.log(err.name);
}
Ana
TypeError
WeakRef
A WeakRef (ES2021) holds a single weak reference to an object. ref.deref() returns the object if it's still alive, or undefined if it has been collected:
let bigReport = { rows: new Array(1000).fill("row") };
const ref = new WeakRef(bigReport);
const report = ref.deref();
console.log(report === bigReport, report.rows.length);
true 1000
After bigReport = null, the object becomes collectable, and at some unpredictable future point ref.deref() starts returning undefined. Typical code always checks:
function getReport() {
let report = reportRef.deref();
if (!report) {
report = buildReport(); // rebuild if it was collected
reportRef = new WeakRef(report);
}
return report;
}
That makes WeakRef useful for caches of large, re-creatable objects: keep them if memory allows, rebuild them if the GC needed the space.
FinalizationRegistry
A FinalizationRegistry lets you request a callback after a registered object has been collected, typically to clean up something associated with it (an entry in a map of WeakRefs, a handle in another system):
const registry = new FinalizationRegistry((heldValue) => {
console.log(`cleaning up after ${heldValue}`);
cacheIndex.delete(heldValue);
});
registry.register(someObject, "report-42"); // held value: anything except someObject itself
The callback receives the held value, never the object (it's already gone).
Weak collections compared
Map / Set | WeakMap / WeakSet | WeakRef | |
|---|---|---|---|
| Keys / members | any value | objects and non-registered symbols | one object or symbol |
| Keeps them alive | yes | no | no |
size, iteration, clear | yes | no | n/a |
| Typical use | general collections | data attached to objects, marking objects | caches of large, rebuildable objects |
Common questions
Why can't I loop over a WeakMap?
Its contents depend on when the garbage collector runs, which isn't predictable. If you could list the keys, your program's output could change depending on GC timing, and listing them would also make them reachable again. The design deliberately hides them.
Is the WeakMap's weak too?
No. Only the key is held weakly. The value is held strongly as long as the key is alive; when the key is collected, the value is released too (unless something else references it). But a value that references its own key keeps nothing alive: the engine handles that case correctly.
How can I see garbage collection happen?
Browser DevTools' Memory panel takes heap snapshots and can force a collection. In Node, node --expose-gc makes a global gc() function available for experiments. Don't rely on either in real code.
Do I need WeakMap if I use #private fields?
Not for privacy. WeakMaps are still the right tool for associating data with objects you don't control, like DOM elements or objects from a library.
Summary
- The garbage collector frees objects that are unreachable; references held by
MapandSetkeep objects reachable. WeakMapandWeakSethold object (or non-registered symbol) keys weakly, so caches and metadata disappear along with their objects; they have no size or iteration.- Use
WeakMapfor per-object caches, metadata and (historically) private data;WeakSetfor marking objects. WeakRefholds one weak reference; always checkderef()forundefined.FinalizationRegistryruns optional cleanup after collection; its timing isn't guaranteed, so never depend on it.
Practice Questions
Which line throws?
const ws = new WeakSet();
ws.add({});
ws.add([]);
ws.add(() => {});
ws.add("id");
Answer
ws.add("id"): strings are primitives, and a WeakSet only accepts objects (including arrays and functions) and non-registered symbols.
A single-page app keeps const tooltips = new Map() mapping DOM elements to tooltip objects. Elements are removed as users navigate. What's the problem and the fix?
Answer
The map keeps removed elements and their tooltips in memory forever (a leak). Use a WeakMap so entries disappear when the elements are no longer referenced anywhere else.
What does new WeakRef(obj).deref() return immediately after creation, while obj is still referenced?
Answer
obj itself. A WeakRef only returns undefined after the target has actually been collected, which can't happen while a strong reference exists.
Write a deepCount(value) function that counts objects in a structure that may contain cycles, using a WeakSet to avoid infinite loops.
Answer
function deepCount(v, seen = new WeakSet()) {
if (typeof v !== "object" || v === null || seen.has(v)) return 0;
seen.add(v);
return 1 + Object.values(v).reduce((n, x) => n + deepCount(x, seen), 0);
}
Previous: JavaScript Set and Map: Unique Values, Key-Value Collections, Set Methods and When to Use Them
Next: Typed Arrays, ArrayBuffer and DataView: Working with Binary Data in JavaScript

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.