So, let’s begin!
To work with any of the Set object methods, firstly, we have to create a set. To do so, we can use the “new Set()” constructor.
let employeeNames = new Set();
The above code will create an empty set as shown in the following output:
The output shows that an empty Set is created, now we can perform any functionality on that set using different set object methods such as append elements, remove elements, etc.
How to use add() method to add elements in a set
Now, we will extend the above example a little bit more to add/append the elements to the Set:
In this example, we added five elements in the set named “employeeNames” using the add() method. Afterward, we utilized the console.log() method to print all the elements stored in the “employeeNames” set on the browser’s console:
The output verifies the working of the add() method.
How to use delete() method to remove elements from a set
Let’s suppose we want to remove “Smith”, and “Paul” from the set “employeeNames”. To do so, we can utilize the delete() method:
The above code block will generate the following output:
The above snippet shows that the delete() method has removed “Smith” and “Paul” from the Set successfully.
How to use clear() method to delete all elements from a set
In this example, we will utilize the clear() method to delete all the items from the set “employeeNames”:
The above code snippet will produce the following results:
The output shows the Set’s size equal to zero; it authenticates the working of the clear() method.
How to check the existence of some specific value in a set using has() method
In this example, we will check the existence of two elements i.e. “Smith”, and “Bryn” using the has() method:
The piece of code will return true if the specified value exists in the set and it will return false if the specified value doesn’t exist in the targeted set:
The output shows that the has() method returns true for the element “smith” as it exists in the set while “Bryn” doesn’t exist in the targeted set therefore the has() method returns false for it.
How to find the size of a set
In this example we will utilize the size property to check the size of the set “employeeNames”:
Following will be the corresponding output for the above-given code:
The output shows the appropriate size of the specified set i.e “employeeNames” set.