JavaScript Tutorial

JavaScript Set add() Method with Examples

TGTeam GyaniPanditNovember 13, 20263 min read

Hello friends! Once you create a Set in JavaScript, the first thing you will want to do is put some values in it. For that we use add(). The add() method inserts a value into a JavaScript Set. If the value is already there, nothing happens, because a Set never stores duplicates. add() returns the Set itself, so you can chain several calls. Let’s see this with a few simple examples.

set.add(value)

Basic Example

const tags = new Set();
tags.add("js");
tags.add("css").add("html");   // chaining
tags.add("js");                // duplicate, ignored
console.log(tags);
console.log(tags.size);

Output:

Set(3) { 'js', 'css', 'html' }
3

The second "js" is silently ignored. No error is thrown, and the size stays 3.

So adding a duplicate is completely safe. Now let’s look at what add() gives back to us.

add() Returns the Same Set

const r = tags.add("react");
console.log(r === tags);

Output:

true

This is why tags.add("css").add("html") works. Note that add() does not tell you whether the value was new. If you need to know, check with has() first, or compare size before and after.

Adding Objects

With numbers and strings things are simple. But with objects, there is a small surprise. Sets compare objects by reference, so two objects that look the same are both added:

const people = new Set();
people.add({ name: "A" });
people.add({ name: "A" });
console.log(people.size);

Output:

2

To keep objects unique by a field, store that field (such as an id) in the Set, or use a Map keyed by id.

Adding Values from an Array

const nums = new Set();
[3, 1, 3, 2, 1].forEach(n => nums.add(n));
console.log([...nums]);

Output:

[ 3, 1, 2 ]

Values keep the order in which they were first added. You can get the same result in one step with new Set([3, 1, 3, 2, 1]).

Now let’s put all of this to work in a small real-world task.

Practical Example: Count Unique Words

const text = "the cat and the hat and the bat";
const words = new Set(text.split(" "));
console.log(words.size, [...words]);

Output:

5 [ 'the', 'cat', 'and', 'hat', 'bat' ]

Common Mistakes

Before we finish, keep an eye on these common mistakes:

  • Passing several values at once. set.add(1, 2, 3) adds only 1; the extra arguments are ignored. Call add() once per value, or loop over an array.
  • Adding an array when you meant its items. set.add([1, 2]) adds the array as one single value. Use [1, 2].forEach(v => set.add(v)) instead.
  • Expecting add() to return true or false. It always returns the Set.

So friends, to sum up: add() puts one value into a Set, quietly ignores duplicates without any error, keeps values in the order they were first added, and returns the Set so you can chain calls like s.add(1).add(2). To add many values at once, loop over an array or simply create the Set from that array. Try the examples in your browser console and you will get the hang of it quickly.

Related: Sets in JavaScript · Set has() · Set delete() · Set size

Turn reading into skillsCertificate courses in AI, Data Science and programming.
Explore Courses