What is WeakSet?

A WeakSet is a collection of objects held weakly: you can add, check and remove objects, but it does not keep them alive, cannot be iterated and has no size.

API

add(obj), has(obj), delete(obj). Values must be objects (or non-registered symbols).

Use cases

WeakSet answers one question: "have I seen or marked this object?", without leaking memory.

  • Tracking processed objects: avoid handling the same node or request twice.
  • Cycle detection in recursive algorithms such as deep clone, deep equal or serialisation.
  • Branding: mark instances created by your own factory or class so other code can verify them (trusted.has(obj)).
  • Flagging DOM elements (initialised, observed) without adding properties to them.

WeakSet vs Set

A Set keeps every member alive forever until you delete it, which is a leak if you only use it as a "seen" marker for short-lived objects. A WeakSet lets the garbage collector remove members automatically.

Limits

You cannot list its contents or know its size, because members can disappear at any time. If you need that, use a Set and clean up yourself.

Code example

js
1// Make sure each element is only initialised once
2const initialised = new WeakSet();
3function initWidget(el) {
4 if (initialised.has(el)) return `${el.id}: already set up`;
5 initialised.add(el);
6 return `${el.id}: set up`;
7}
8const card = { id: "card-1" };
9console.log(initWidget(card)); // card-1: set up
10console.log(initWidget(card)); // card-1: already set up
11
12// Cycle-safe traversal
13function countNodes(node, seen = new WeakSet()) {
14 if (node === null || typeof node !== "object" || seen.has(node)) return 0;
15 seen.add(node);
16 return 1 + Object.values(node).reduce((sum, child) => sum + countNodes(child, seen), 0);
17}
18const a = { name: "a" };
19const b = { name: "b", a };
20a.b = b; // cycle
21console.log(countNodes(a)); // 2 - no infinite loop
22
23// Branding: only objects created by our factory are trusted
24const trusted = new WeakSet();
25function createToken(value) {
26 const token = Object.freeze({ value });
27 trusted.add(token);
28 return token;
29}
30const real = createToken("abc");
31const fake = { value: "abc" };
32console.log(trusted.has(real), trusted.has(fake)); // true false

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.

Open in study app