Skip to main content

What is WeakSet?

WeakSet is a "lightweight" version of Set, which stores only objects and does so via a weak reference (hence the name Weak).

It is meant for situations where you want to store unique objects but not stop the garbage collector (GC) from removing them once they are no longer used anywhere else.

Creating a WeakSet

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
  • Stores only objects, not primitives. (Try adding a string or a number and you get an error.)

    javascript
    ws.add(123); // TypeError
  • If obj1 is no longer used anywhere else, the garbage collector removes it automatically from the WeakSet.

WeakSet methods

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

No size, forEach, keys, values, entries methods

  • because WeakSet cannot be iterated.

Main difference from Set:

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

Example: automatic removal

javascript
let obj = { id: 1 }; const ws = new WeakSet(); ws.add(obj); console.log(ws.has(obj)); // true obj = null; // now the object is no longer reachable // the object will automatically be removed from memory by the garbage collector
  • After obj = null the object becomes reachable only from the WeakSet, so the GC (garbage collector) can remove it.
  • This makes WeakSet convenient for storing temporary or cached objects.

Real usage example

Tracking which objects have already been "processed":

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 is automatically removed from the WeakSet

In short:

PropertyValue
TypeA collection of unique objects
PrimitivesNot allowed
Garbage collectorCan remove elements
IterationNot possible
Methodsadd, delete, has
Common useCaching, "processed" markers, private data

Summary: WeakSet is a collection of unique objects that are automatically removed from memory once there are no other references to them.

It is great for temporary markers and caching, it does not fit if you need to store data permanently or iterate over it.

Short Answer

Interview ready
Premium

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