The Set clear() method in JavaScript is used for the removal of all the elements from a set and making it empty.
Syntax:
mySet.clear();
Parameters:
- This method does not accept any parameters.
Return Value:
- Returns an undefined value.
Example 1: Emptying set using Set clear() method
Explanation:
- In the above example we Initializes a new Set called myset using the Set() constructor.
- Adds the element 23 to the set using the add() method and prints the set along with its size.
- Clears the set using the clear() method and prints its size again, which confirms it as 0.
Example 2: Emptying set using Set clear() method
OutputSet(3) { 'Manchester', 'London', 'Leeds' }
3
0 Explanation:
- In the above example we Initializes a new Set named myset using the Set() constructor.
- Adds three strings ("Manchester", "London", and "Leeds") to the set using the add() method and prints the set along with its size.
- Clears the set using the clear() method and prints its size again, confirming it as 0 since the set is empty.
We have a complete list of Javascript Set methods, to check those please go through this Sets in JavaScript article.
Supported Browsers: