
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
What are JavaScript Sets
A set is an abstract data type that can store certain values, without any particular order, and no repeated values. It is a computer implementation of the mathematical concept of a finite set. Unlike most other collection types, rather than retrieving a specific element from a set, one typically tests a value for membership in a set.
You should use sets, whenever you want to store unique elements in a container for which the order doesn't matter and you mainly want to use it to check for membership of different objects. Sets are also useful when you want to perform operations like union, intersection, difference, like you do in mathematical sets.
The Set object lets you store unique values of any type, whether primitive values or object references.
Note −Because each value in the Set has to be unique, the value equality will be checked.
Creating and using sets
let mySet = new Set(); mySet.add(1); mySet.add(1); mySet.add(1); // Added only once console.log(mySet.size) // Not considered equal mySet.add({}); mySet.add({}); console.log(mySet.size) let a = {}; mySet.add(a); mySet.add(a); // added once only console.log(mySet.size)
Output
1 3 4
Note that the objects added here are not considered equal. This is because these objects reference different memory spaces. This causes them to not be equal.