Open In App
Related Articles

JavaScript Set clear() Method

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

The Set.clear() method in JavaScript is used for the removal of all the elements from a set and making it empty. No arguments are required to be sent as parameters to the Set.clear() method and it returns an undefined return value.

Syntax:

mySet.clear();;

Parameters:

This method does not any accept any parameters.

Return Value:

This method returns an undefined value.

Example 1: 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

Example 2: 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

Supported Browsers:

  • Google Chrome:  38+
  • Firefox: 19+
  • Internet Explorer: 11+
  • Opera: 25+
  • Edge: 12+
  • Safari: 08+

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

We have a Cheat Sheet on Javascript where we covered all the important topics of Javascript to check those please go through Javascript Cheat Sheet-A Basic guide to JavaScript.  



Last Updated : 11 Jan, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads