Skip to main content

WeakSet in JavaScript

WeakSet is a "lightweight" version of Set that stores only objects and holds them by a weak reference, which is where the word Weak comes from. It is designed for situations where you want to keep unique objects around but must not prevent the garbage collector (GC) from removing them once they are no longer used anywhere else.

Theory

TL;DR

  • WeakSet stores objects only, primitives throw a TypeError.
  • References to its elements are weak: the GC may remove an object while it still sits in the collection.
  • Only three methods exist: add(value), delete(value), has(value).
  • There is no size, forEach, keys, values or entries, because the collection cannot be iterated.
  • Elements are unique, exactly like in a Set.
  • Typical uses: "already processed" marks, a temporary cache, private data.

Quick example

javascript
const ws = new WeakSet(); const obj1 = { name: 'Alice' }; const obj2 = { name: 'Bob' }; ws.add(obj1); ws.add(obj2); console.log(ws.has(obj1)); // true

What matters here:

  • The collection stores objects only, not primitives. Trying to add a string or a number fails immediately.

    javascript
    ws.add(123); // TypeError: Invalid value used in weak set
  • If obj1 is no longer used anywhere, the garbage collector removes it automatically and the entry disappears from the WeakSet.

WeakSet methods

MethodDescriptionExample
add(value)adds an objectws.add(obj)
delete(value)removes an objectws.delete(obj)
has(value)checks for presencews.has(obj)

Note that there are no size, forEach, keys, values or entries methods, because a WeakSet cannot be iterated. That is not a whim of the specification: the GC removes elements at an unpredictable moment, so any iteration would produce a non deterministic result.

The main difference from Set

PropertySetWeakSet
Can store primitivesYesNo, objects only
Elements are weakly held (GC may remove them)NoYes
Can be iterated (for...of, size)YesNo
Used for temporary referencesRarelyOften

Automatic removal from memory

javascript
let obj = { id: 1 }; const ws = new WeakSet(); ws.add(obj); console.log(ws.has(obj)); // true obj = null; // the object is no longer reachable // the object will be removed from memory automatically by the garbage collector

How this works:

  • After obj = null the object is reachable only from the WeakSet, and such a reference does not count as a strong one, so the GC is free to remove it.
  • That is exactly what makes WeakSet convenient for holding temporary or cached objects: you never have to clean up by hand.

A practical example: tracking processed objects

javascript
const processed = new WeakSet(); function process(obj) { if (processed.has(obj)) { console.log('Already processed'); return; } processed.add(obj); console.log('Processing:', obj.name); } const user = { name: 'Alice' }; process(user); // Processing: Alice process(user); // Already processed // after user = null the object disappears from the WeakSet automatically

Here the WeakSet acts as an "invisible flag" on the object: we do not bolt a service field such as obj.__processed onto it, we do not pollute the data structure, and we do not keep the object alive longer than necessary.

In short

PropertyValue
TypeA collection of unique objects
PrimitivesNot allowed
Garbage collectorMay remove elements
IterationImpossible
Methodsadd, delete, has
Common useCaching, "processed" marks, private data

Summary: WeakSet is a collection of unique objects that are removed from memory automatically once no other references to them remain. It is excellent for temporary marks and caching, and a poor fit when data has to be stored permanently or iterated over.

Common mistakes

  • Trying to add a primitive. ws.add('text') or ws.add(5) is a TypeError, only an object can be a member.
  • Looking for size or a loop. Counting the elements or walking over them is impossible by design; use a regular Set for that.
  • Storing long lived data in a WeakSet. With no external references the entry may vanish at any time, this is not a storage.
  • Assuming removal is instant. The GC runs whenever it sees fit, so has() is not guaranteed to return false right after you drop the last reference.
  • Confusing it with WeakMap. A WeakSet stores the objects themselves, a WeakMap stores "object to value" pairs.
  • Turning it into a result cache. A WeakSet remembers only the fact of membership; to attach a value to an object you need a WeakMap.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.