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
let myset = new Set();
myset.add(23);
console.log(myset);
console.log(myset.size);
myset.clear();
console.log(myset.size);
|
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
let myset = new Set();
myset.add( "Manchester" );
myset.add( "London" );
myset.add( "Leeds" );
console.log(myset);
console.log(myset.size);
myset.clear();
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
Last Updated :
05 Mar, 2024
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...