- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Explain sets in JavaScript?
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.
<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.
<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
- Related Articles
- Adding two Sets in Javascript
- Subtract two Sets in Javascript
- What are javascript sets?
- When should you use sets in Javascript?
- Cartesian product of two sets in JavaScript
- Finding union of two sets in JavaScript
- Algorithm for sorting array of numbers into sets in JavaScript
- How to know whether a value is searched in Javascript sets?
- How to make your code faster using JavaScript Sets?
- Sets in C#
- Python Program to find Duplicate sets in list of sets
- Explain Comments in JavaScript
- Explain typecasting in Javascript?
- Explain hoisting in JavaScript
- How to split a Dataset into Train sets and Test sets in Python?

Advertisements