“Set” Methods to Perform Various Operations
- add() method: It is used to add new elements in a Set. If the same element/object is already present in the Set, it does not add it again.
- delete() method: For deleting any specified element, use the “delete()” method. After deleting, it outputs “true”.
- clear() method: It removes/eliminates all elements from a Set.
- has() method: For verifying whether the element exists in the Set or not, use the “has()” method.
- size: It gives the number of all the existing elements of the Set.
Example 1: Add Elements in Set
Create a new Set using the “new Set()” constructor:
Call the add() method to add elements in Set:
As you can see, we have added six elements in Set, but the output shows the “5” elements because Set does not contain duplicate values:
Example 2: Delete an Element From Set
Here, we will delete “14” from Set using the “delete()” method:
The output shows “true”, which means “14” is successfully deleted from Set:
Example 3: Check if Set Contains Specific Element
Now, check whether “14” exists in Set or not. For that, call the “has()” method:
Output displays “false,” which means “14” is deleted from the created jsSet:
Example 4: Remove All Elements From Set
For removing all the elements from Set, use the “clear()” method:
Example 5: Check Set Size
Check the size of the Set using the “size” property:
The output shows “0”, which means all the elements of the Set are deleted: