How to add an element to a set - JavaScript

Mo Ibra

Mo Ibra

Dec 23, 2022

In this article we will learn how to add an element to a set.

It is very common to add an element to a set in JavaScript.


Problem

Now we have a problem, which is that we want to add an element to a set.

Now let's imagine we have a set like this:

// Set
[1, 2, 3, 4]

And we want to add new element to this set, to become like this:

[1, 2, 3, 4, 5]

How to solve this problem?

Fortunately, we have a built-in function that add elements to set called add.


Add an elements to a set using add

We can use add method to add an element to a set.

For Example

// set
const set = new Set([1, 2, 3, 4]);

// Before adding element
console.log(set);

// Add element
set.add(5);

// After adding element
console.log(set);

Output

Set(5) { 1, 2, 3, 4, 5 }

You should know you can chain multiple calls together.

// set
const set = new Set([1, 2, 3, 4]);

// Chaining elements
set.add(5)
    .add(6)
    .add(7)
    .add(8)

// Result:
console.log(set);

Output

Set(8) { 1, 2, 3, 4, 5, 6, 7, 8 }

The keys in the set are unique, and this means that if you use more than one element with the same value, only one element will be added (last one)

// set
const set = new Set([1, 2, 3, 4]);

// Chaining elements
set.add(5).add(5).add(5);

// After adding element
console.log(set);

Output

Set(5) { 1, 2, 3, 4, 5 }

As you noticed, the country field has been updated.


Thank you for reading

Thank you for reading my blog. 🚀

Suggestions For More Articles: