Wednesday, September 25, 2024
Google search engine
HomeLanguagesJavascriptJavaScript Set clear() Method

JavaScript Set clear() Method

The Set.clear() method in JavaScript is used for the removal of all the elements from a set and make 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:

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:

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.  

RELATED ARTICLES

Most Popular

Recent Comments