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,

  1. Create a new Set object numbers with initial values 1, 2, and 3.
  2. Use the clear() method to remove all elements from the numbers Set.
  3. Log the numbers Set to the console using console.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,

  1. Create a new, empty Set object emptySet.
  2. Use the clear() method to clear the emptySet.
  3. Log the emptySet to the console using console.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,

  1. Create a new Set object letters with initial values 'a' and 'b'.
  2. Use the add() method to add the value 'c' to the letters Set.
  3. Use the delete() method to remove the value 'a' from the letters Set.
  4. Use the clear() method to remove all remaining elements from the letters Set.
  5. Log the letters Set to the console using console.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.