JavaScript Set clear() Method
The Set clear() method in JavaScript is used for the removal of all the elements from a set and making it empty.
Set clear() Method Syntax
mySet.clear();
Set clear() Method Parameters
This method does not accept any parameters.
Set clear() Method Return Value
Returns an undefined value.
Set clear() Method Examples
Example 1: Emptying set using Set clear() method
Below is an example of the Set.clear() method.
Javascript
// Create a new set using Set() constructor let myset = new Set(); // Append new elements to the // set using add() method myset.add(23); // Print the modified set console.log(myset); console.log(myset.size); // The clear() method will remove // all elements from the set myset.clear(); // This will return 0 as there // are no elements present in the Set console.log(myset.size); |
Output
Set(1) { 23 } 1 0
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
Below is an example of Set.clear() method.
Javascript
// Create a new set using Set() constructor let myset = new Set(); // Append new elements to the // set using add() method myset.add( "Manchester" ); myset.add( "London" ); myset.add( "Leeds" ); // Print the modified set console.log(myset); console.log(myset.size); // The clear() method will remove // all elements from the set myset.clear(); // This will return 0 as the set is empty console.log(myset.size); |
Output
Set(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
Contact Us