Skip to content
jshacks.dev
Fundamentals

WeakMap and WeakSet in JavaScript for Memory Safe Caches

WeakMap and WeakSet hold their keys weakly, so an entry goes away once nothing else references the key. See per-object caches, metadata and the limits.

7 min read
Summarize in AI
Flat illustration of a rising bar chart and a gauge, with the JavaScript, Redis, Prometheus, NGINX and TypeScript logos.

A Map used as a cache has a quiet failure mode: it holds a reference to every key, so the objects it was keyed by can never be collected, even long after the rest of the program has stopped using them. The cache grows for the life of the process. WeakMap and WeakSet exist for exactly this case. They hold their keys weakly, which means the collection does not count as a reason to keep a key alive, and entries vanish when their keys become unreachable. The trade-off is a deliberately small interface, and the rest of the topic is learning what you can still do with it. This post covers the interface, the three jobs these collections do well, the limits and how to test behavior you cannot observe directly. Output is from Node.js 24 as an ES module. The collection that holds keys strongly is covered in the post on Sets and Maps, and the collector itself in the post on garbage collection.

The interface is small on purpose

A WeakMap has set, get, has and delete. A WeakSet has add, has and delete. That is the whole API.

JavaScript
const metadata = new WeakMap();
const seen = new WeakSet();

const user = { name: "Ada" };
const other = { name: "Grace" };

metadata.set(user, { visits: 3 });
seen.add(user);

console.log(metadata.get(user), metadata.get(other));
console.log(metadata.has(user), seen.has(user), seen.has(other));

console.log(metadata.delete(user), metadata.has(user));

console.log(typeof metadata.size, typeof metadata.forEach, typeof metadata.keys, typeof metadata.clear);
console.log(typeof seen.size, typeof seen[Symbol.iterator]);

for (const bad of ["text", 42, null]) {
  try {
    metadata.set(bad, 1);
  } catch (error) {
    console.log(error.name + ": " + error.message);
  }
}
Text
{ visits: 3 } undefined
true true false
true false
undefined undefined undefined undefined
undefined undefined
TypeError: Invalid value used as weak map key
TypeError: Invalid value used as weak map key
TypeError: Invalid value used as weak map key

The calls behave like their Map and Set relatives. The properties that would let you observe the contents are missing: no size, no iteration, no clear(). A primitive key is rejected, because a string or a number has no identity that could ever become unreachable. The reason for the missing members is that the entries can disappear at any time the collector runs, so a count or a list would be unstable and would reveal collection timing.

Per-object caches

The classic use is caching a computed result per object. Keyed by the object, the entry lives exactly as long as the object does.

JavaScript
const areaCache = new WeakMap();
let computations = 0;

function area(shape) {
  if (areaCache.has(shape)) return areaCache.get(shape);
  computations += 1;
  const value = shape.width * shape.height;
  areaCache.set(shape, value);
  return value;
}

const rectangle = { width: 4, height: 5 };

console.log(area(rectangle), area(rectangle), area(rectangle));
console.log(computations);

const copy = { ...rectangle };
console.log(area(copy));
console.log(computations);

rectangle.width = 10;
console.log(area(rectangle));
console.log(computations);
Text
20 20 20
1
20
2
20
2

The first object was computed once and read from the cache twice. The copy is a different object, so it was computed separately. The last lines expose the weakness of any cache keyed by identity: the object changed, and the cache still returned the old answer, because nothing told it the input was different. Cache only results of immutable objects, or invalidate on change. With a plain Map, the same cache would also keep every rectangle alive for as long as the map existed, and a long-running process that creates many short-lived shapes would grow.

Metadata on objects you do not own

Libraries often need to attach data to objects that belong to someone else, such as DOM nodes, request objects or class instances, without modifying them. A WeakMap does that with no property added to the object and no risk of a name clash.

JavaScript
const listeners = new WeakMap();

function onChange(target, callback) {
  const list = listeners.get(target) ?? [];
  list.push(callback);
  listeners.set(target, list);
}

function emit(target, value) {
  for (const callback of listeners.get(target) ?? []) callback(value);
}

const field = { id: "email" };
const frozen = Object.freeze({ id: "locked" });

onChange(field, (v) => console.log("field changed to", v));
onChange(frozen, (v) => console.log("frozen changed to", v));

emit(field, "[email protected]");
emit(frozen, "[email protected]");
console.log(Object.keys(field), Object.isFrozen(frozen));
Text
field changed to [email protected]
frozen changed to [email protected]
[ 'id' ] true

Both targets received listeners, including the frozen one, which could not have had a property added. Neither object shows any trace of the data in its own keys. When the targets are dropped, the listener lists go with them. In a browser, DOM nodes are the standard key, so a library can track state for elements that the page later removes, with no cleanup code.

Private data per instance

Before #private fields, a WeakMap was the standard way to keep truly private state for a class. It still is the choice when the state must be attached from outside the class body.

JavaScript
const secrets = new WeakMap();

class Session {
  constructor(token) {
    secrets.set(this, { token });
  }

  get masked() {
    return "*".repeat(secrets.get(this).token.length);
  }
}

const session = new Session("abc123");

console.log(session.masked);
console.log(Object.keys(session), JSON.stringify(session));
console.log(session.token);
Text
******
[] {}
undefined

The token lives in the map and not on the instance, so it never appears in Object.keys(), in JSON or in a console print. Anyone who can import secrets could read it, so the privacy depends on the map staying inside the module. The post on private class fields shows the built-in alternative, which does not need a module-level variable and is the better choice in new code.

Marking objects with a WeakSet

A WeakSet answers "have we seen this object". It is the right structure for visited tracking in graph and tree walks, and for cycle detection.

JavaScript
function hasCycle(node, path = new WeakSet()) {
  if (typeof node !== "object" || node === null) return false;
  if (path.has(node)) return true;

  path.add(node);
  const found = Object.values(node).some((child) => hasCycle(child, path));
  path.delete(node);

  return found;
}

const tree = { name: "root", children: [{ name: "leaf" }] };
const loop = { name: "loop" };
loop.self = loop;

console.log(hasCycle(tree));
console.log(hasCycle(loop));

const brand = new WeakSet();
class Token {
  constructor() {
    brand.add(this);
  }
  static isToken(value) {
    return brand.has(value);
  }
}

console.log(Token.isToken(new Token()), Token.isToken({}));
Text
false
true
true false

The first function walks an object graph, adds each node to the path and removes it on the way back, so only real cycles are reported and shared subtrees are not. The second is a brand check: the set records which objects were built by the constructor, and isToken reads it. The set holds no strong reference, so a token that is dropped is collected normally.

Symbols as keys

Since ES2023, non-registered symbols are valid weak keys, which allows a symbol to act as a unique, collectable identity.

JavaScript
const registry = new WeakMap();

const local = Symbol("job");
registry.set(local, "pending");
console.log(registry.get(local));

try {
  registry.set(Symbol.for("shared"), "no");
} catch (error) {
  console.log(error.name + ": " + error.message);
}
Text
pending
TypeError: Invalid value used as weak map key

A symbol made with Symbol() worked as a key. A symbol from the global registry, Symbol.for(), did not, because the registry keeps it alive forever, so a weak entry on it could never be collected.

Testing what you cannot observe

You cannot assert that an entry was collected, because collection timing is up to the engine, and a test that forces it with --expose-gc is a test of the runtime and not of your code. Test the behavior you control: that the cache returns the stored value, that a different object misses, and that the public API never exposes the weak collection. For leak detection, measure memory growth over many iterations in a profiling session, as in the post on memory management, and compare a Map version with a WeakMap version.

A leak you can recognize

The symptom of a strong cache is steady memory growth in a process that handles many short-lived objects, such as a server that keys a Map by request or a UI that keys it by component instance. Heap snapshots show the map with a growing number of entries whose keys are objects nothing else uses. Swapping Map for WeakMap in that one place is the smallest possible fix, and it works only if you never needed to iterate the map. If you did, the real fix is an explicit lifecycle: remove the entry when the object is disposed, which is more work and makes the ownership visible.

Where weak collections are the wrong tool

If you must count entries, enumerate them, expire them on a timer or clear them all at once, you want a Map with an explicit policy. If the keys are strings or numbers, a weak collection cannot hold them. If a cache must keep an object alive, because it is expensive to rebuild and may be needed again, a weak reference is the wrong strength. And if the data belongs to the object, a normal property or private field is simpler.

Do not rely on collection happening promptly or at all. A weak collection avoids leaks and makes no promise about when memory returns.

The collections are defined in the specification under WeakMap objects and WeakSet objects, and MDN's pages on WeakMap and WeakSet describe the interface and the key rules.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.