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.

Updated on: 18-Sep-2019

101 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements