JavaScript Sets

JavaScript Sets


JavaScript Sets
 
In this tutorial, you will learn about the JavaScript Set object provided by ES6 (Ecmascript 6). A set is a collection of items which are unique i.e., no element can be repeated. Sets in ES6 are ordered: elements of the set can be iterated in the insertion order. Set can store any types of values whether primitive or objects. 
 
Set Methods
Method
Description
new Set()
Creates a new Set
add()
Adds a new element to the Set
delete()
Removes an element from a Set
has()
Returns true if a value exists
clear()
Removes all elements from a Set
forEach()
Invokes a callback for each element
values()
Returns an Iterator with all the values in a Set
keys()
Same as values()
entries()
Returns an Iterator with the [value,value] pairs from a Set
The Syntax of the JavaScript Set is as follows:
new Set([it]);
 
Example1 – Pass an Array to the new Set() constructor: 
Output
Example2 - Add values to a set Create a Set and add literal values:
Output