JavaScript Set clear() Method Tutorial

In this section, we will learn what the Set clear() method is and how to use it in JavaScript.

What is JavaScript Set clear() Method?

If we want to clear all the elements of a `Set` object, we can use the `clear()` method.

After calling this method, all the elements in that Set object will be removed. So the size of the object becomes 0 afterward.

The method takes no argument and we just use the target `Set` object to call this method.

JavaScript Set clear() Method Syntax:

clear()

clear() Function Parameters:

The method does not take an argument.

clear() Function Return Value:

The method does not have a return value.

Example: using Set clear() method in JavaScript

const collect = new Set();

collect.add("Jack");

collect.add("Jack");

collect.add("Omid");

collect.add("John");

console.log(`The size of the collection before calling the clear method: ${collect.size}`);

collect.clear();

console.log(`The size of the collection after calling the clear method: ${collect.size}`);

Output:

The size of the collection before calling the clear method: 3

The size of the collection after calling the clear method: 0
Facebook
Twitter
Pinterest
LinkedIn

Top Technologies