Skip to content
Related Articles

Related Articles

JavaScript Set clear() Method

View Discussion
Improve Article
Save Article
  • Last Updated : 03 Mar, 2022
View Discussion
Improve Article
Save Article

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




<script>
 
    // 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);
</script>

Output:

Set(1) { 23 }
1
0

Example 2:

Javascript




<script>
 
    // 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);
</script>

Output:

Set(3) { 'Manchester', 'London', 'Leeds' }
3
0

Supported Browsers:

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

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!