JavaScript Set clear()
Syntax & Examples
Set.clear() method
The clear() method of the Set object in JavaScript removes all elements from the Set object, effectively making it empty.
Syntax of Set.clear()
The syntax of Set.clear() method is:
clear()
This clear() method of Set removes all elements from the Set object.
Return Type
Set.clear() returns value of type undefined
.
✐ Examples
1 Using clear() to empty a Set
In JavaScript, we can use the clear()
method to remove all elements from a Set object.
For example,
- Create a new Set object
numbers
with initial values 1, 2, and 3. - Use the
clear()
method to remove all elements from thenumbers
Set. - Log the
numbers
Set to the console usingconsole.log()
.
JavaScript Program
const numbers = new Set([1, 2, 3]);
numbers.clear();
console.log(numbers);
Output
Set {}
2 Using clear() on an already empty Set
In JavaScript, using the clear()
method on an already empty Set object will not cause any errors.
For example,
- Create a new, empty Set object
emptySet
. - Use the
clear()
method to clear theemptySet
. - Log the
emptySet
to the console usingconsole.log()
.
JavaScript Program
const emptySet = new Set();
emptySet.clear();
console.log(emptySet);
Output
Set {}
3 Using clear() after adding and removing elements from a Set
In JavaScript, we can use the clear()
method after adding and removing elements from a Set object to empty it completely.
For example,
- Create a new Set object
letters
with initial values 'a' and 'b'. - Use the
add()
method to add the value 'c' to theletters
Set. - Use the
delete()
method to remove the value 'a' from theletters
Set. - Use the
clear()
method to remove all remaining elements from theletters
Set. - Log the
letters
Set to the console usingconsole.log()
.
JavaScript Program
const letters = new Set(['a', 'b']);
letters.add('c');
letters.delete('a');
letters.clear();
console.log(letters);
Output
Set {}
Summary
In this JavaScript tutorial, we learned about clear() method of Set: the syntax and few working examples with output and detailed explanation for each example.