What is the set.add() method in JavaScript?
Overview
The set.add() function in JavaScript is used to insert an element in the set.
The image below shows the visual representation of the set.add() function:
In JavaScript, a set is a particular instance of a list in which all inputs are unique.
Note: If there are duplicates, the set will only keep the first instance. For example:
{'Tom','Alsvin','Eddie','Tom'}will result in{'Tom','Alsvin','Eddie'}.
Syntax
set_name.add(element)
// where the set_name is the name of the set.
Parameter
This function requires an element as a parameter.
Return value
This function inserts the element sent as a parameter in the set.
Code
The code below shows how to use the set.add() function in JavaScript:
const set_1 = new Set(["Tom","Alsvin"]);//set containing value before insertconsole.log("set_1 elements before insert: ",set_1);//inserting element in setset_1.add("Eddie")//set containing value after insertconsole.log("set_1 elements after insert: ", set_1);//trying duplicate insertionset_1.add("Tom")//set containing value after duplicate insertionconsole.log("set_1 elements after duplicate insert: ", set_1);
Explanation
-
Line 1: We create a set with two values
{'Tom','Alsvin'}and name itset_1. -
Line 6: We add a new element
Eddieinset_1using theadd()method. -
Line 11: If we try to add a duplicate name, for example,
Tom, then it ignores it and returns the same set.