The clear() method of the Set object in JavaScript removes all elements from the Set object, effectively making it empty.
The syntax of Set.clear() method is:
clear()
This clear() method of Set removes all elements from the Set object.
Set.clear() returns value of type undefined
.
In JavaScript, we can use the clear()
method to remove all elements from a Set object.
For example,
numbers
with initial values 1, 2, and 3.clear()
method to remove all elements from the numbers
Set.numbers
Set to the console using console.log()
.const numbers = new Set([1, 2, 3]);
numbers.clear();
console.log(numbers);
Set {}
In JavaScript, using the clear()
method on an already empty Set object will not cause any errors.
For example,
emptySet
.clear()
method to clear the emptySet
.emptySet
to the console using console.log()
.const emptySet = new Set();
emptySet.clear();
console.log(emptySet);
Set {}
In JavaScript, we can use the clear()
method after adding and removing elements from a Set object to empty it completely.
For example,
letters
with initial values 'a' and 'b'.add()
method to add the value 'c' to the letters
Set.delete()
method to remove the value 'a' from the letters
Set.clear()
method to remove all remaining elements from the letters
Set.letters
Set to the console using console.log()
.const letters = new Set(['a', 'b']);
letters.add('c');
letters.delete('a');
letters.clear();
console.log(letters);
Set {}
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.