JavaScript WeakSet

Beginner
6 min read
Updated: Nov 2026
3 examples
Collections

Definition and Usage

In JavaScript, a WeakSet is a collection of objects. Each object can be in it only once. You create one with new WeakSet() and then use just three methods: add(), delete(), and has().

The word weak means the set does not keep its objects alive. When the rest of your program stops using an object, the JavaScript engine is free to clean it up, and the WeakSet forgets it. Because that can happen at any moment, a WeakSet has no size and cannot be looped over.

You use a WeakSet to mark objects without changing them: "already visited", "already processed", "created by my factory". This page teaches the ideas; the WeakSet Methods index lists every method guide.

A WeakSet is a quiet checklist.

You can tick an object, untick it, and ask if it is ticked. You cannot ask how many are ticked, or list them.

JavaScript Syntax

Common ways to create a WeakSet and use it:

JavaScript
const seen = new WeakSet();            // empty set
const user = { name: "Ada" };

seen.add(user);                        // add an object
const known = seen.has(user);          // true
seen.delete(user);                     // true, removed
const both = new WeakSet([user, {}]);  // fill it from an array

Core Ideas

Ideas every WeakSet tutorial builds on:

IdeaExampleRemember
Createnew WeakSet()Starts empty; an array (or other iterable) of objects is optional
AddweakSet.add(obj)Objects only; returns the set
CheckweakSet.has(obj)true or false, never throws
RemoveweakSet.delete(obj)true if it was there
Same objectset.has(sameVariable)Compared by reference, not by contents
No sizetypeof set.sizeIt is "undefined"; you cannot count
No looptypeof set.forEachIt is "undefined"; you cannot list

What "Weak" Means

A normal collection, like an array or a Set, keeps every item reachable. As long as the collection exists, so do its items. A WeakSet does not. If nothing else in your program points to an object, being in a WeakSet is not enough to keep it in memory.

When the garbage collector (the engine's memory cleaner) removes such an object, it is simply gone from the set. You cannot watch this happen and you cannot predict when it does. So never write code that waits for an object to disappear. Use the three methods to say what you know right now.

The same idea is behind WeakMap (objects with extra data attached) and WeakRef (a single weak pointer). They are separate tools; this tutorial covers the WeakSet.

WeakSet vs Set

QuestionSetWeakSet
What can it hold?Any valueObjects only (and symbols made with Symbol(), since ES2023)
Does it keep objects alive?Yes, while the set existsNo, it holds them weakly
Can I get its size?Yes, sizeNo
Can I loop over it?YesNo
Can I clear it?Yes, clear()No, make a new WeakSet
Which methods?add, delete, has, and moreadd, delete, has only

When to Use a WeakSet

A WeakSet fits when you only need to answer "have I seen this object before?":

JobHow the WeakSet helps
Visited objectsMark each object you walk through, so loops between objects stop.
Already processedSkip an object you have handled, without adding a flag to it.
Brand checkRemember objects made by your own factory and accept only those.
DOM elementsNote which elements already have a listener, without keeping removed elements in memory.

JavaScript Examples

Three short programs that show how a WeakSet behaves.

Example 1 — Handle Each Object Only Once

A WeakSet remembers which orders were already handled, so the same order is never processed twice.

JavaScript
const processed = new WeakSet();

function handle(order) {
  if (processed.has(order)) {
    return "skipped " + order.id;
  }
  processed.add(order);
  return "handled " + order.id;
}

const order = { id: "A1" };
console.log(handle(order));          // handled A1
console.log(handle(order));          // skipped A1
console.log(handle({ id: "A1" }));   // handled A1
add() tutorial

How It Works

  1. Check, then mark. The function asks processed.has(order) first. On the first call the answer is no, so it adds the order and reports "handled".
  2. The same object is remembered. The second call passes the very same order variable, so has() says yes and the order is skipped.
  3. Looks do not count. The last call builds a new object with the same id. It is a different object, so a WeakSet treats it as new and handles it.

Example 2 — What a WeakSet Does Not Have

Make a WeakSet from an array of objects, then see which familiar Set features are missing.

JavaScript
const a = { n: 1 };
const b = { n: 2 };
const set = new WeakSet([a, b]);

console.log(set.has(a));          // true
console.log(typeof set.size);     // undefined
console.log(typeof set.clear);    // undefined
console.log(typeof set.forEach);  // undefined
console.log(typeof set.add);      // function
has() tutorial

How It Works

  1. Fill it at creation. Passing [a, b] to the constructor calls add() for each item, so has(a) is true straight away.
  2. Three things are missing. There is no size, no clear(), and no forEach(). typeof reports "undefined" for each of them.
  3. Only three methods exist. add is a function, and so are delete and has. Those three are the whole API.

Example 3 — A Set and a WeakSet Side by Side

A regular Set stores anything and knows its size. A WeakSet accepts only objects and refuses a string.

JavaScript
const strong = new Set();
const weak = new WeakSet();
const item = { id: 1 };

strong.add("hello");
strong.add(item);
console.log(strong.size);      // 2

weak.add(item);
console.log(weak.has(item));   // true

try {
  weak.add("hello");
} catch (err) {
  console.log(err.name);       // TypeError
}
console.log(weak.delete(item));  // true
delete() tutorial

How It Works

  1. A Set takes anything. The regular set holds a string and an object, and it can count them: strong.size is 2.
  2. A WeakSet takes objects. item goes in without trouble, and weak.has(item) confirms it.
  3. A string is turned away. Adding "hello" throws a TypeError, which the catch prints. Removing item afterwards still returns true.

WeakSet Method Groups

A WeakSet has only three methods. Each one has a full tutorial with examples you can run in the browser.

MethodUse it to
add()Put an object into the set (objects only)
delete()Remove an object and learn if it was there
has()Ask whether an exact object is in the set

Full list with the constructor: WeakSet Methods index.

Frequently Asked Questions

A WeakSet is a collection of objects with no duplicates. You add objects, remove them, and ask whether one is inside. It holds them weakly, which means it does not stop the engine from cleaning up an object that nothing else uses.
A Set can hold any value, has a size, and can be looped over. A WeakSet holds only objects, has no size, and cannot be looped over, because its contents may disappear when objects are cleaned up.
Objects in a WeakSet can be removed by the engine at any time you cannot see. If you could count or list them, results would change unpredictably. So only add(), delete(), and has() exist.
Use it to mark objects without changing them: visited nodes in a graph, objects already processed, items already shown, or a simple private brand check. If the objects are not needed, the marks do not keep them in memory.
No. add() throws a TypeError for numbers, strings, booleans, null, and undefined. Use a regular Set for those. Since ES2023, a symbol made with Symbol() is also allowed as a value in recent engines.

Browse every WeakSet method

Open the index for add(), delete(), and has(), plus what a WeakSet does not have.

WeakSet Methods index →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

16 people found this page helpful