How do you add an element to a Set object in JavaScript?

Before we can add elements to a Set object in JavaScript, we first need to create a Set object. We can create a new Set object using the new Set() constructor.

// Create a new Set object
const mySet = new Set();

In this example, we create a new Set object called mySet. This Set object is initially empty.

Adding Elements to a Set:

To add an element to a Set object in JavaScript, we can use the add() method. The add() method adds a new element to the Set object if it does not already exist.

For example:

// Add an element to the Set
mySet.add("apple");

In this example, we add the string "apple" to the Set using the add() method. Note that if you try to add an element that already exists in the Set, it will be ignored as Sets only allow unique values.

// Adding a duplicate element to the Set
mySet.add("apple");

// The Set still only has one element
console.log(mySet); // Set { 'apple' }

In this example, we add "apple" to the Set again, but it is ignored since it already exists in the Set.

Adding Multiple Elements to a Set:

We can add multiple elements to a Set object in JavaScript using the add() method as well. We can chain the add() method calls to add multiple elements to the Set.

// Add multiple elements to the Set
mySet.add("banana").add("orange").add("pear");

// The Set now has multiple elements
console.log(mySet); // Set { 'apple', 'banana', 'orange', 'pear' }

Using the Spread Operator:

Another way to add multiple elements to a Set is to use the spread operator. The spread operator allows us to expand an iterable (such as an array) into individual elements. We can use the spread operator to add all the elements from an array to a Set object.

For example:

// Add elements from an array to the Set using the spread operator
const moreFruits = ["pineapple", "kiwi", "grape"];
mySet.add(...moreFruits);

// The Set now contains all the elements from both arrays
console.log(mySet); // Set { 'apple', 'banana', 'orange', 'pear', 'pineapple', 'kiwi', 'grape' }

Thank you for reading, and let’s have conversation with each other

Thank you for reading my article. Let’s have conversation on Twitter and LinkedIn by connecting.

Read more: