What is the set.clear() method in Javascript?
Overview
The set.clear() function in Javascript is used to remove all of the elements from the set.
The illustration below shows the visual representation of the set.clear() function:
In Javascript, a set is a particular instance of a list in which all inputs are unique.
Note: If there are duplicates, then the set will only keep the first instance. For example:
{'Tom','Alsvin','Eddie','Tom'}will result in{'Tom','Alsvin','Eddie'}.
Syntax
set_name.clear()
// where the set_name is the name of the set.
Parameter
This function does not require any parameters.
Return value
This function is used to erase all of the set’s elements.
Code
The code below shows how to use the set.clear() function in Javascript:
const set_1 = new Set(["Tom","Alsvin", "Eddie"]);//set containing value before clearconsole.log("set_1 elements before Clear: ",set_1);//clearing all the elements from setset_1.clear()//set containing value after clearconsole.log("set_1 elements after Clear: ", set_1);
Explanation
-
Line 1: We create a set with three values
{'Tom','Alsvin','Eddie'}and name itset_1. -
Line 6: We clear all the elements of the set using the
set.clear()method.