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

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

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

var programming = new Set();  
var itr=programming.entries();  
document.writeln("Size for Programming Set Object before delete(): "+ set.size+"<br>");  
document.writeln("Size for Programming Set Object before delete(): "+set.size); 

JavaScript Set Object has() , value() example

var names = new Set();  
set.forEach(function display(value1,value2,set)   
	document.writeln('key[' + value1 + '] = ' + value2+"<br>");  
 document.writeln(names.has("Matthew"));    // returns true or false