JavaScript WeakSet add() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
WeakSet

Definition

weakSet.add(value) puts an object into a WeakSet. If the object is already there, nothing changes, so the set never holds the same object twice. The method returns the WeakSet itself, which lets you chain several add() calls. The set holds each object weakly: it does not keep an object alive once the rest of your program has stopped using it.

Remember
const seen = new WeakSet();
const user = { name: "Ada" };

seen.add(user)     → returns seen (the same WeakSet)
seen.add(user)     → nothing changes, no duplicates
seen.add("Ada")    → TypeError (a string is not an object)

Objects, arrays and functions are all allowed.

Syntax

Call add on a WeakSet and pass one object. The constructor does the same for each item of an iterable.

JavaScript
const weakSet = new WeakSet();
weakSet.add(value)

const another = new WeakSet([objectA, objectB]);
CallWhat it does
weakSet.add(value)Add one object to the set and return the set.
weakSet.add(a).add(b)Chain calls, because every call returns the same WeakSet.
new WeakSet([a, b])Create a set and add each object of the array at the start.

Part of ES2015 together with WeakSet itself. Every value you pass must be an object, or you get a TypeError.

Library declarations
JavaScript
weakSet.add(value)   // returns weakSet

// weakSet.size      does not exist
// weakSet.clear()   does not exist
// weakSet.forEach() does not exist

Parameters

ParameterDescription
valueThe object to add. It can be a plain object, an array, a function, a class instance, or a DOM node. A number, string, boolean, null, undefined, or BigInt throws a TypeError. Since ES2023 a symbol that was made with Symbol() is also allowed.

Return Value

Return ValueDescription
WeakSetThe same WeakSet you called add() on, not a copy. Use it to chain another call, for example set.add(a).add(b).

JavaScript Examples

Example 1 — Add Objects and Chain the Calls

Add an object, check what add() returns, then chain two more calls in a single line.

JavaScript
const marked = new WeakSet();
const first = { id: 1 };
const second = { id: 2 };
const list = [10, 20];

console.log(marked.add(first) === marked);  // true

marked.add(second).add(list);
console.log(marked.has(first));             // true
console.log(marked.has(second));            // true
console.log(marked.has(list));              // true
Try It Yourself

How It Works

  1. A set from add(). The first line prints true because marked.add(first) hands back marked itself, not a new set.
  2. One line, two objects. Since each call returns the set, .add(list) can follow .add(second) straight away.
  3. Arrays count too. An array is an object in JavaScript, so list is accepted. All three lookups with has() print true.

Example 2 — Visit Each Linked Object Once

Pages that link to each other form a loop. A WeakSet remembers which pages were visited, so the walk stops instead of running forever.

JavaScript
const visited = new WeakSet();
const order = [];

function walk(node) {
  if (visited.has(node)) {
    return;
  }
  visited.add(node);
  order.push(node.name);
  node.links.forEach(function (next) {
    walk(next);
  });
}

const home = { name: "Home", links: [] };
const docs = { name: "Docs", links: [] };
const blog = { name: "Blog", links: [] };
home.links.push(docs, blog);
docs.links.push(blog, home);  // links back to home: a loop
blog.links.push(home);

walk(home);
console.log(order.join(" > "));  // Home > Docs > Blog
console.log(order.length);       // 3
Try It Yourself

How It Works

  1. Mark before you go deeper. The function calls visited.add(node) before it follows any link, so a page is already marked when a later link points back to it.
  2. Loops end quietly. Docs and Blog both link to Home. visited.has(node) is true for Home, so those calls return at once.
  3. Nothing is stored on the pages. The pages stay plain objects with a name and links. The marks live only in the WeakSet, so you never add a visited: true property to each page.

Example 3 — Primitives Throw a TypeError

Try to add five primitive values. Each one fails with a TypeError, while an object works fine.

JavaScript
const set = new WeakSet();
const attempts = [42, "text", true, null, undefined];

attempts.forEach(function (value) {
  try {
    set.add(value);
    console.log(String(value) + " -> added");
  } catch (err) {
    console.log(String(value) + " -> " + err.name);
  }
});

console.log(set.add({ ok: true }) === set);  // true
Try It Yourself

How It Works

  1. Wrap risky input. The try block runs set.add(value). When it throws, the code jumps to catch and the "added" line is skipped.
  2. Print the error name only. Message wording changes between browsers, so the example logs err.name, which is always TypeError. It also shows that null and undefined fail.
  3. An object goes in. The last line adds { ok: true } and compares the result with set. It prints true because adding an object works.

Browser & Runtime Support

WeakSet and its add() method are part of ES2015 (ES6), so they work in every modern browser.

✓ Baseline · ES2015

WeakSet.prototype.add()

Supported in Chrome 36+, Firefox 34+, Safari 9+, Edge 12+, Node.js, and Deno. Internet Explorer 11 has WeakMap but not WeakSet.

ES2015 Supported for years
Google Chrome 36 and newer
Supported
Mozilla Firefox 34 and newer
Supported
Apple Safari 9 and newer
Supported
Microsoft Edge 12 and newer
Supported
Node.js All current releases
Supported
Deno All releases
Supported
Internet Explorer No WeakSet, not even IE 11
Not supported
weakSet.add() Very wide

Bottom line: Safe in every modern browser and runtime. Only the newer ES2023 rule that lets a Symbol() value be added is limited to recent versions, such as Node.js 20 or newer.

Frequently Asked Questions

It returns the same WeakSet you called it on, not a copy. That is why you can chain calls like set.add(a).add(b).add(c).
A WeakSet can only hold objects. Numbers, strings, booleans, null, undefined, and BigInt values are rejected with a TypeError. Use a regular Set when you need to store primitive values.
Nothing. The second add() finds the object already in the set and does not add it again. It still returns the WeakSet and does not throw.
Since ES2023 you can add a symbol made with Symbol(), but not one made with Symbol.for(), which still throws a TypeError. Older browsers reject every symbol, so objects are the safe choice.
WeakSet has been available since Chrome 36, Firefox 34, Safari 9, and Edge 12, and in Node.js and Deno. Internet Explorer does not have it. Objects are accepted everywhere; only symbol values need a recent engine.

Next: delete()

Remove an object from the WeakSet and learn what the true and false results mean.

delete() tutorial →

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.

11 people found this page helpful