Set Object in JavaScript

The blog provides the details about the JavaScript Set object. The JavaScript Set object is used to store the elements with unique values supporting the primitive values or object references. 

  • The JavaScript Set object uses the Key-Value pair internally to store the elements. 
  • The JavaScript Set object does not support duplicate values
  • The JavaScript Set object allows the iteration of the stored elements in the insertion order.

Syntax for Java Script Set object

new Set([iterable])

Methods for JavaScript Set Object

Set MethodsDescription
add()Method allows to add the specified values to the Set object.
clear()Method allows to remove all the elements from the Set object.
delete()Method allows to delete the specified element from the Set object.
entries()Method allows to return an object of Set iterator with an array of [value, value] for each element.
forEach()Method allows to execute the specified function once for each value.
has()Method allows to indicate if the given Set object contains specified element.
values()Method allows to return an object of Set iterator with the values for each element.

JavaScript Set Object add() , clear() Example

<script>  
var subjects = new Set();  
subjects.add("English");  
subjects.add("Maths");  
subjects.add("Science");  
for (let elements of subjects) {  
 document.writeln(elements+"<br>");  
}
 
document.writeln("Size for Subject Set Object before clear() : "+ set.size+"<br>");  
set.clear();  
document.writeln("Size for Subject Set Object after clear(): "+set.size);   
</script> 

JavaScript Set Object add() , entries() , delete() example

<script>
var programming = new Set();  
programming.add("C").add("C++").add("Java");   
var itr=programming.entries();  
for(i=0;i<programming.size;i++)  
  {  
	document.writeln(itr.next().value+"<br>");  
  }  
 
document.writeln("Size for Programming Set Object before delete(): "+ set.size+"<br>");  
set.delete("C++");  
document.writeln("Size for Programming Set Object before delete(): "+set.size); 
</script>

JavaScript Set Object has() , value() example

<script>
var names = new Set();  
names.add("Robert").add("Matthew").add("John");
set.forEach(function display(value1,value2,set)   
{  
	document.writeln('key[' + value1 + '] = ' + value2+"<br>");  
})  
 document.writeln(names.has("Matthew"));    // returns true or false
}  
for(i=0;i<names.size;i++)  
  {  
	document.writeln(itr.next().value+"<br>");  
  }  
</script>