Learn about how to use and when to use Set in JavaScript.

The Set object allows you to create a collection of unique values(each value can occur only once).
Set can contain any type of value (primitives or object reference).
Set stores elements in the insertion order.
The Set doesnβt containβs keys π like a Map object.
The uniqueness of elements of the Set are checked using the SameValueZero algorithm. This algorithm is similar to === (strict equal) except in one case where NaN === NaN evaluates to true, so that multiple NaN is not inserted in the Set.
Creating aΒ Set
Syntax: new Set([iterable]) β returns a Set object.
var set1 = new Set([1, 2, 1, 3, 4, 5]);
set1; // Set(5) {1, 2, 3, 4, 5} ; duplicate values are removed.
Creating an empty set
var set2 = new Set();
Properties
size β Returns the number of elements in the Set
var number = new Set([1,2,3,4,5])
number.size ;
Methods
add()
The add() method appends the element passed to the end of a Set object and returns the Set object.
var fruits = new Set(['π', 'π', 'π', 'π' ]);
fruits.add('π');
fruits; // Set(5) {'π', 'π', 'π', 'π', 'π'};
When we try to add duplicate values it is not inserted.
fruits.add('π'); // already present in the set
fruits; // Set(5) {'π', 'π', 'π', 'π', 'π'};
The add method is chain-able
fruits
.add('π')
.add('π')
.add('π');
fruits; // Set(8) {"π", "π", "π", "π", "π", β¦}
Adding objects to Set
var set = new Set();
set.add({i : 10});
set.add({i : 10});
set; //Set(2) {{β¦}, {β¦}}
// Even-though objects look same, each object has different reference, so they are not ===
// An object reference means that it compares the memory address of the object and not the actual key/value pairs contained in the object.
--------------------------------------------------------------------
var obj = {i :100};
set.add(obj);
set.add(obj);
// Now the obj points to same object reference so it is not inserted
--------------------------------------------------------------------
obj.i =1000;
// the value in the set is changed because we are storing the address.
has()
The has() method returns true if an element with the specified value exists in a Set object, and false if the value is not present in the SetΒ .
Syntax: has(valueToBeChecked) β returns either true or false.
var fruits = new Set(['π', 'π', 'π', 'π' ]);
fruits.has('π'); //true
fruits.has('π'); //false
has method with object
var set = new Set();
var obj = {i :100};
set.add(obj);
set.has(obj); // true
set.has({i : 100}); //false, because they are different object reference.
values()
The values() method returns a new Iterator object that contains the values for each element in the Set object in insertion order.
var fruits = new Set(['π', 'π', 'π', 'π' ]);
fruits.values(); // SetIterator {"π", "π", "π", "π", "π", β¦}
--------------------------------------------------------------------
//use destructor to print only the values
console.log(...fruits.values())
or
var fruitsArray = ([...fruits.values]);
entries()
The entries() method returns a new Iterator object that contains an array of [value, value] in insertion order.
There is no key in a Set so it returns in the format of [value, value]Β .
var fruits = new Set(['π', 'π']);
fruits.entries(); SetIterator {"π" => "π", "π" => "π"}
--------------------------------------------------------------------
// you can use for...of
for(var [key ,value] of fruits.entries()) {
console.log(key, value);
}
delete()
The delete() method removes the specified element from a Set object.
SyntaxΒ : delete(valueToBeDeleted)
Returns true if an element in the Set is deleted, otherwise it returns false.
var fruits = new Set(['π', 'π']);
fruits.delete('π'); //true
fruits; //Set(1) {"π"}
fruits.delete('π'); false.
clear()
The clear()method empties theSet object.
var fruits = new Set(['π', 'π']);
fruits.size; // 2
fruits.clear();
fruits.size; // 0
Using forEach on a Set object:
let print= function(key , value, set) {
console.log(value);
}
var fruits = new Set(['π', 'π']);
fruits.forEach(print)
//output
π
π
Tips andΒ Tricks
- When we pass a string as an argument when creating a
Set, then it creates a set with all characters as separate elements.
var text = 'LEARN';
var mySet = new Set(text);
//Set(5) {"L", "E", "A", "R", "N"}
2. Removing duplicate elements from an array
var names= [ 'John', 'Brandi', 'Tony', 'John'];
var uniqueNames = [...new Set(names)]
uniqueNames = [ 'John', 'Brandi', 'Tony'];
3. How array and set are different
-
Setobjects store unique values, whereas array can have duplicate values - In an array, we need to use the
indexOfmethod to check the availability of element in the array, but in a set we can use thehasmethod, which is compared to be faster thanindexOfmethod.

- The value
NaNcannot be found withindexOfin an array. -
Setobjects let you delete elements by their value. With an array, you would have to splice based on an element’s index.
You can read about map πΊ in details here.
If you find this helpful surprise π me here.
Share if you feel happy π π πΒ .
Follow Javascript Jeepπ if you feel worthy.