JavaScript – Set


What is a Set ?

A set is a collection of items which are unique and no elements can be repeated.

What is a Set in Javascript ?

A Set is an object which is used to store elements with unique values.

Elements in the set can be iterated in the insertion order.

Javascript Set can store any types of values either primitive or objects.

Free online javascript course !!!

Click to Learn More about – Javascript online learning

Syntax :

new Set([iterable])  

iterable :


If an iterable object is passed, all of its elements will be added to the new Set.

And If we don’t specify this parameter or its value is null, the new Set is empty.

Example :

<script>
			var a = new Set();
			var b = new Set([10,20,30,40,50]);
			var c = new Set("String Value");
			var d = new Set(["Abdul","Sachin","Rahul","Viru"]);
			console.log(a);
			console.log(b);
                        console.log(c);
                        console.log(d);
		</script>

Output :

How does Set work in javascript ?

A set object uses the key/value pair concept internally.

A set object should not contain duplicate values.


A set object iterates its elements in insertion order.

There are some methods for Set Object listed below,

SnoMethodsDescription
1add()It adds the specified values to the Set object.
2clear()It removes all the elements from the Set object.
3delete()It deletes the specified element from the Set object.
4entries()It returns an object of Set iterator that contains an array of [value, value] for each element.
5forEach()It executes the specified function once for each value.
6has()It indicates whether the Set object contains the specified value element.
7values()It returns an object of Set iterator that contains the values for each element.