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:

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 insert
console.log("set_1 elements before insert: ",set_1);
//inserting element in set
set_1.add("Eddie")
//set containing value after insert
console.log("set_1 elements after insert: ", set_1);
//trying duplicate insertion
set_1.add("Tom")
//set containing value after duplicate insertion
console.log("set_1 elements after duplicate insert: ", set_1);

Explanation

  • Line 1: We create a set with two values {'Tom','Alsvin'} and name it set_1.

  • Line 6: We add a new element Eddie in set_1 using the add() method.

  • Line 11: If we try to add a duplicate name, for example, Tom, then it ignores it and returns the same set.

Free Resources