In JavaScript, to add to a set, you can use the add() method. add() will add an element to the set if the element is not already in the set.

var numbersSet = new Set([1, 2, 3]);

numbersSet.add(4);

console.log(numbersSet);

#Output:
{1, 2, 3, 4}

You can also use the Spread Operator (…) to add multiple elements from an array to a set.

var numbersSet = new Set([1, 2, 3]);

var arr1 = [4,5];
var combinedSet1 = new Set([ ...numbersSet, ...arr1 ]);

console.log(combinedSet1);

#Output:
{1, 2, 3, 4, 5}

var set2 = new Set([6,7]);
var combinedSet2 = new Set([ ...combinedSet1, ...set2 ]);

console.log(combinedSet2);

#Output:
{1, 2, 3, 4, 5, 6, 7}

When working with collections of data in JavaScript, the ability to easily add items or change the collection is important.

One such case where you may want to modify a collection is if you want to add elements to a set in JavaScript.

To add on item to a set in JavaScript, you can use the add() method. add() will add an element to the set if the element is not already in the set.

Below is our example again of how you can use add() method to add one item to a set in JavaScript.

var numbersSet = new Set([1, 2, 3]);

numbersSet.add(4);

console.log(numbersSet);

#Output:
{1, 2, 3, 4}

Adding Multiple Items to Set in JavaScript with the Spread Operator (…)

If you want to add multiple items to a set in JavaScript, then you could use the add() method multiple times, or use the Spread Operator (…).

Below shows you how to add multiple elements to a set using Spread Operator (…) in JavaScript.

var numbersSet = new Set([1, 2, 3]);

var arr1 = [4,5];
var combinedSet1 = new Set([ ...numbersSet, ...arr1 ]);

console.log(combinedSet1);

var set2 = new Set([6,7]);
var combinedSet2 = new Set([ ...combinedSet1, ...set2 ]);

console.log(combinedSet2);

#Output:
{1, 2, 3, 4, 5}
{1, 2, 3, 4, 5, 6, 7}

Hopefully this article has been useful for you to learn how to use JavaScript to add items to a set.

Categorized in:

JavaScript,

Last Update: March 11, 2024