This post will discuss how to add values to a Set in JavaScript.

There are several ways to add values to a set in JavaScript. A set is a data structure that stores unique values of any type. To add values to a set, we can use the following functions:

1. Using Set.add() function

This is the simplest and most common way to add values to a set. The Set.add() function inserts a new element with a specified value into the set, if there is not an element with the same value already in the set. We can pass the value to the add() function as an argument and chain multiple calls to add to insert multiple values. The function chaining works since the add() function returns the set object itself. For instance:

Download  Run Code

 
The Array.forEach() function executes a callback function for each element of an array. We can use this function to add each element of an array to an existing set using the Set.add() function. For instance:

Download  Run Code

2. Using Set Constructor

We can also create a set from an array or any other iterable object, such as a string, a map, or another set. We need to pass the array or the iterable object to the Set() constructor, which creates a new set from the values of the iterable object. This will automatically add all the unique values from the iterable object to the set. We can also use the spread operator (…) to create a new set from an existing array or an existing set or both. For instance:

Download  Run Code

That’s all about adding values to a Set in JavaScript.