Explain sets in JavaScript?

JavascriptObject Oriented ProgrammingProgramming

Sets

The Set is a new object type provided by ES6. It is nothing but a collection of values, which are unique. The values can be either simple primitives such as strings, integers etc. or complex object types such as object literals or arrays.

Syntax 

new Set([iterable]);

parameters

iterable

It is an iterable object whose elements will be added to the new set. In case if the iterable is not provided or a null value is passed then the new set will be empty. 

Example

Since a set allows only unique values, the length of the object after adding some of existing elements in the set will not be changed.

 Live Demo

<html>
<body>
<script>
   var set1 = new Set(["a","a","b","b","c"]);// no of unique elements - 3(a, b and c)
   set1.add('c').add('d')                    // Two elements were added (c,d)
   set1.forEach(alphabet => {                // In total 7 elements but only 4 unique values
   document.write(`alphabet ${alphabet}!`);
   document.write("</br>");
   });
   document.write(set1.size);               // it displays 4 since sets accept only unique values.
</script>
</body>
</html>

Output

alphabet a!
alphabet b!
alphabet c!
alphabet d!
4

Example-2 

Sets also display boolean value. They check whether a provided element is available or not in the given set and executes a boolean output.

 Live Demo

<html>
<body>
<script>
   var set1 = new Set(["a","a","b","b","c"]);
   set1.add('c').add('d')
   set1.forEach(alphabet => {
   document.write(`alphabet ${alphabet}!`);
   document.write("</br>");
   });
   document.write(set1.has('a'));  // it display true because a is there in set1
   document.write("</br>");    
   document.write(set1.has('8'));   // it display false because there is no 8 in the set1.
   document.write("</br>");
   document.write(set1.size);  // displays only unique values because only unique values are accepted
</script>
</body>
</html>

Output

alphabet a!
alphabet b!
alphabet c!
alphabet d!
true
false
4
raja
Published on 04-Jun-2019 12:39:33
Advertisements