Open In App

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.






// 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

Example 2: Emptying set using Set clear() method

Below is an example of Set.clear() method.




// 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

We have a complete list of Javascript Set methods, to check those please go through this Sets in JavaScript article.

Supported Browsers


Article Tags :