JavaScript set add() method explanation with example:
JavaScript Set provides a method called add(), by using which we can add one element to a set. JavaScript Set object can be used to hold unique values of any type.
We can create a new set object by using its constructor Set(). Once created, we can add elements to this object by using the add() method.
Definition of add():
add is an instance method of Set and this method is used to append a new element with a specific value to the end.
This method returns a Set object.
The syntax of add is:
set.add(value);
value is the value to add to the set.
Example of add() method:
Let’s take an example of add and how to use it:
let givenSet = new Set();
givenSet.add('hello');
givenSet.add(' ');
givenSet.add('world');
console.log(givenSet);
for(const element of givenSet){
console.log(element);
}
It will print the below output:
Set(3) { 'hello', ' ', 'world' }
hello
world
As you can see here, add retuns a Set object. So, we can use it in a chain:
let givenSet = new Set();
givenSet.add('hello').add(' ').add('world');
console.log(givenSet);
for(const element of givenSet){
console.log(element);
}
It will print the same output.
Add the same item multiple times:
If we try to add the same item for multiple times, it will not add that item. Because, a set can hold only unique values. For example,
let givenSet = new Set();
givenSet.add('hello').add(' ').add('world').add('hello').add('world');
console.log(givenSet);
It will print:
Set(3) { 'hello', ' ', 'world' }
As you can see here, it is not adding the same string twice.
Example with numbers:
We can also use Set with numbers. For example,
let givenSet = new Set();
givenSet.add(1).add(2).add(3).add(4).add(5).add(6).add(7).add(8).add(9).add(10);
console.log(givenSet);
It is adding numbers from 1 to 100 to the Set givenSet.
It will print:
Set(10) { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }
You might also like:
- JavaScript program to mask the start digits of a phone number
- JavaScript Map forEach method example
- How to add one second delay in JavaScript
- JavaScript example to add padding to the end of a string using padEnd
- JavaScript Array every method explanation with example
- JavaScript program to check if an array is a subarray of another array
- JavaScript program to delete an item from a set