This post will discuss how to initialize a Set in JavaScript.

Initializing a set means creating a new set object and optionally adding some values to it. There are several methods to initialize a set in JavaScript, depending on what kind of values we want to add to the set and how we want to pass them. Here are some of the common functions:

1. Using Set() constructor

We can pass an array of values to the Set() constructor to create a new set that contains the unique values from the array. This is a simple and convenient way to initialize a set with multiple values at once. For instance:

Download  Run Code

 
We can even pass a string of characters to the Set() constructor to create a new set that contains the unique characters from the string. This is useful when we want to initialize a set with individual characters or symbols. For instance:

Download  Run Code

 
Another option is to create a new set object from another iterable object, such as another set, using the Set() constructor. For example, this code creates a new set from an existing set.

Download  Run Code

2. Using add() function

We can use the add() function of the Set object to add one or more elements to an existing set object. The add() function takes a value as an argument and adds it to the set if it does not already exist. We can create an empty set by calling the Set() constructor without any arguments, and then use the add() function to add values to the set one by one. This is useful when we want to initialize a set dynamically or conditionally. For instance:

Download  Run Code

 
The add() function returns the set object itself, allowing us to chain multiple calls to it. For example, this code creates an empty set and then adds three elements using chaining:

Download  Run Code

That’s all about initializing a Set in JavaScript.