Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

Set.prototype.add — adding a value to a set

Set.prototype.add(value) adds a single value to a set if it is not already present. It mutates the existing Set and returns that same object, allowing calls to be chained.

Version: ECMAScript and Web APIs; exact feature edition and browser support reviewed per entry; Node 24 in repository does not prove browser API support

Syntax

set.add(value)

set.add(value) adds one value to an existing Set object. If the value is already present, the set remains unchanged. The method always returns the same set, not a boolean indicating insertion, so you can write set.add(a).add(b). A new value goes at the end of iteration order; adding an existing value again does not change its position.

Uniqueness follows SameValueZero comparison: NaN duplicates NaN, and -0 and +0 represent the same element; zero is stored as +0. Objects are compared by identity, not contents. Two separately created {} objects are therefore distinct elements, but adding the same reference again does not increase size.

add does not expand arrays or other iterables: set.add([1, 2]) adds one array. Calling it without an argument adds undefined. The method requires a receiver with internal Set data; Set.prototype.add.call({}, 1) throws a TypeError.

Examples

const values = new Set();
const returned = values.add("blue").add("green").add("blue");
console.log(returned === values);
console.log(values.size);
console.log([...values].join(","));
values.add(NaN).add(NaN).add(-0).add(+0);
console.log(values.size);

Result

true
2
blue,green
4

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources