JavaScript Set add(): Add Values to a Set

Tech reviewed: Deepak Prasad
JavaScript Set add(): Add Values to a Set

A JavaScript Set stores unique values. Use the add() method to add a value to a Set. If the value already exists, it is not added again, so the Set remains unique.

set.add(value) returns the Set itself, which means you can chain multiple add() calls.

Environment: Node.js v20.18.2. After each runnable snippet, the following paragraph states the expected console output (order and values).


Method 1: Add Values to a Set

Create a Set and call add() for each value.

javascript
const tags = new Set();
tags.add("js");
tags.add("css");
tags.add("js");

console.log("set-add-values:", [...tags].join(","));
Output

You should see one line logging set-add-values: js,css.

The second "js" is ignored because Set values are unique.


Method 2: Chain add() Calls

Because add() returns the Set object, calls can be chained.

javascript
const tags = new Set();
const returned = tags.add("js").add("css").add("js");

console.log("set-add-same:", returned === tags);
Output

You should see one line logging set-add-same: true.

This is useful when adding several values during setup.


Method 3: Check Set Size After Adding

Use size to count unique values.

javascript
const values = new Set([1, 1, 2]);
values.add(3);

console.log(values.size);
Output

You should see one line logging 3.

size counts unique values, not the number of times add() was called.


Method 4: Add Objects to a Set

Objects are unique by reference.

javascript
const set = new Set();
set.add({ id: 1 });
set.add({ id: 1 });

console.log(set.size);
Output

You should see one line logging 2.

The two objects look the same, but they are different object references.


Common Questions About JavaScript Set add()

What does Set add return?

set.add(value) returns the same Set object, which allows method chaining.

Does Set add allow duplicates?

No. If the Set already contains the value, adding it again does not create a duplicate.

How do I add multiple values to a Set?

Use chained add() calls, loop over an array, or create the Set from an array: new Set(array).


Summary

Use Set.add() to add values to a JavaScript Set while keeping the collection unique. The method returns the Set itself, so you can chain calls. Primitive values are compared by value, while objects are compared by reference. Use size, has(), and array conversion with [...set] when you need to inspect the Set after adding values.


Official Documentation

Olorunfemi Akinlua

Boasting over five years of experience in JavaScript, specializing in technical content writing and UX design. With a keen focus on programming languages, he crafts compelling content and designs user-friendly interfaces to enhance digital …

  • JavaScript
  • Web Design