# JavaScript - Tidbits

Like *sets and relations* in mathematics, JavaScript has built-in objects to demonstrate such logics and make developers’ life more logical, easy going and fun.

JavaScript has a special object called ‘Set’. A Set() is a constructor that creates a set object and holds a few methods as explained here and with help of those methods it can perform different operations of sets like union, intersection, difference etc.

**Syntax:**  
`<declaration> <identifier> = new Set()`  
**or**  
`<declaration> <identifier> = new Set(<array>)`

**Eg:**

```javascript
const a = new Set([1,2,3,4,5])
```

A Set in JavaScript is a constructor which can only be initialized with `new` operator. An empty set can also be created and utilized later to add, modify or delete some data with the help of its instance methods.

Like other objects in JavaScript (such as Map), Set has generic properties and methods such as `size`, `has()`, `keys()`, `values()`.

For example, let's consider a new set:

```javascript
const setSample = new Set([0.1,22,3,43,54,0.5,101,121,200])
setSample.size    // returns: 9
setSample.has(200)  // returns: true
setSample.has(2010)  // returns: false
setSample.keys() // returns set Iterator
setSample.values() // returns set Iterator
```

Every Set by default contains a special instance methods like `keys()` and `values()` which in return creates an iterator object.

* #### In JavaScript all built-in iterators inherit from Iterator class
    

Consider 2 sets A and B and lets go through some basic math:  
**<mark>Union:</mark>** <mark>A∪B</mark>  
**<mark>Intersection:</mark>** <mark>A∩B</mark>  
**<mark>Difference:</mark>** <mark>A - B ≣ A \ B</mark>  
**<mark>SymmetricDifference:</mark>** <mark>(A \ B) ∪ (B \ A)</mark>  
**<mark>isSubsetOf:</mark>** <mark>A⊆B</mark>  
**<mark>isSupersetOf:</mark>** <mark>A⊇B</mark>  
**<mark>isDisjointFrom:</mark>** <mark>A∩B = ∅</mark>

A Set constructor holds a collection of instance methods which are used to handle these mathematical operations in JavaScript efficiently.

Let's consider 2 arrays namely ‘arrayA’ and ‘arrayB’ and thier sets ‘setA’ and ‘setB’ respectively:

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1728568126696/e916f61e-9e11-4809-bd8a-19e9d1039064.png align="center")

```javascript
let arrayA = [0,2,5,7,8,4,6,1], arrayB = [3,9,10,1,12,21,33,42,2];
```

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1728569169877/40072254-62bb-4b3a-b34b-9bd33e20d8b2.png align="center")

```javascript
const setA = new Set(arrayA), setB = new Set(arrayB);
```

### Union of Sets

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1728646888117/150c9237-851c-4d34-922b-56c21383c9c5.png align="center")

**<mark>Use: </mark>** <mark>To find unique features among set-like data entities.</mark>

Syntax: `<set A>.union(<set B>)`

Eg:

```javascript
setA.union(setB);
// results in:  Set(15) {0,2,5,7,8,4,6,1,3,9,10,12,21,33,42}
```

It ignores the duplicates elements and makes a set of unique elements.

#### Intersection of Sets:

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1728646473901/713947be-6b60-47b3-b511-66d2b75ea322.png align="center")

**<mark>Use: </mark>** <mark>To identify similarities between two set-like data entities.</mark>

Syntax: `<set A>.intersection(<set B>)`

Eg:

```javascript
setA.intersection(setB);
// results in:  Set(2) {2,1}
```

It gets the common elements among them and ignores the rest of the elements.

#### Difference of Sets:

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1728647628475/dffefe6f-10d1-4e40-a689-084ef32bda44.png align="center")

**<mark>Use:</mark>** <mark>To find the features that are present only in the first one among the two set-like data entities.</mark>

Syntax: `<set A>.difference(<set B>)`

Eg:

```javascript
setA.difference(setB);
// results in:  Set(6) {0,5,7,8,4,6}

setB.difference(setA);
// results in:  Set(7) {3,9,10,12,21,33,42}

setA.difference(setA);
// results in:  Set(0) {}
```

#### Symmetric Difference of Sets:

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1728647638666/f53afefa-322f-4c6f-8314-58721c57c331.png align="center")

**<mark>Use:</mark>** <mark>To get rid of the common features among the two data entities. In other words, it is quiet opposite to Intersection.</mark>

Syntax: `<set A>.symmetricDifference(<set B>)`

Eg:

```javascript
setA.symmetricDifference(setB);
// results in Set(13) {0,5,7,8,4,6,3,9,10,12,21,33,42}

setB.symmetricDifference(setA)
// results in Set(13) {3,9,10,12,21,33,42,0,5,7,8,4,6}
```

#### Disjoint Sets:

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1728647835505/ac7b0d13-ee25-4f60-8ded-3f363c906330.png align="center")

**<mark>Use:</mark>** <mark>To verity if both of them do not match each other.</mark>

Syntax: `<set A>.isDisjointFrom(<set B>)`

Eg:

```javascript
setA.isDisjointFrom(setB);
// results in Set() {}
```

#### Subset of Sets:

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1728648255962/9c0e23d8-22d5-49cd-9a51-31cf96bd4ef7.png align="center")

**<mark>Use:</mark>** <mark>To verify if the first data entity is a part of the second one.</mark>

Syntax: `<set A>.isSubsetOf(<set B>)`

Eg:

```javascript
let arrayA = [9,10,1,21], arrayB = [3,9,10,1,12,21,33,42,2];
const setA = new Set(arrayA), setB = new Set(arrayB);
setA.isSubsetOf(setB);
// result is true

setA.isSubsetOf(setA);
// result is true
```

#### Superset of Sets:

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1728648274766/01fe758e-835c-4661-90e1-2389c9df6036.png align="center")

**<mark>Use:</mark>** <mark>To verify if the first data entity has the second one as a part of it.</mark>

Syntax: `<set A>.isSupersetOf(<set B>)`

Eg:

```javascript
let arrayA = [9,10,1,21], arrayB = [3,9,10,1,12,21,33,42,2];
const setA = new Set(arrayA), setB = new Set(arrayB);
setB.isSupersetOf(setA);
// result is true

setB.isSupersetOf(setB);
// result is true
```

Besides these regular math operations, Set constructor also holds other instance methods to operations like CRUD, iterations etc.

`add() delete() clear() size() has() entries() keys() values() forEach() Symbol.iterator next()`

Examples of these operations:  
Let’s consider arrays p1,p2,p3,p4 and p5.

```plaintext
let p1 = ['ravi',25,'Indian', 'graduate','techie']
let p2 = ['Ravi',32,'Indian', 'graduate','no-techie']
let p3 = ['Ronald',23,'American','highSchool','techie']
let p4 = ['Arun',32,'Indian','graduation','techie']
let p5 = ['Dennis',40,'American', 'under-graduate','non-techie']
```

Using a Set constructor we can create different sets out of each and every array as shown here:

```javascript
const setP1 = new Set(p1) 
const setP2 = new Set(p2) 
const setP3 = new Set(p3) 
const setP4 = new Set(p4) 
const setP5 = new Set(p5)
```

```javascript
let countryCriteria = ['Indian', 'American','European']
let ageCriteria = [23,25,32,40]
const setCC = new Set(countryCriteria)
const setAC = new Set(ageCriteria)
```

### Advantages of Sets

* Sets avoid unnecessary iterations through arrays' or objects' data.
    
* They do not modify original array of data.
    

### Real-time scenarios

There are some real-time scenarios where Sets make developers' life easy such as when any two data entities (sets) are considered:

* Useful to find unique entries in a data collection like stores, books, etc.
    
* Missing entries from a large data sets (like Censuses in a city) can be found easily with minimal coding efforts.
    
* Find out if an existing user is entering / leaving the chat rooms or from online meeting areas.
    
* In a large scalable applications, compare and filter the datasets based on certain predefined features and restrict their access to a particular domain routes in that application.
    
* Identify similar molecular structures in various chemical composition data.
    
* Identify and keep track of similar cyber attacks that happen frequently on a large scale of networking pipelines.
    

### Order of Complexity

Iterators use index numbers to locate their elements where as Sets use <mark>Hash tables</mark>. Hash table is a data structure and it is a generalization of an ordinary array whose expected time of search reasonably is O(n) where an average value of n=1.

Hash tables are more performant while executing operations like data searching and sorting etc on large data sets. They work on key-index combinations instead of iterating through an entire array of elements.

Order of Complexity of sets can be represented as O(log N), sometimes O(N). It depends on the complexity of the logic written.

Let’s take an example of 2 arrays, find common elements in both of them and remove similar ones from the resultant array. Perform this operation in 2 ways:

* Without using Sets
    
* Using Sets
    

```javascript
 let arrResult=[];
 let arr1 = [1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6,7,8,9,20,1,2,3,4,5,6,7,8,9,30,1,2,3,4,5,6,7,8,9,40,1,2,3,4,5,6,7,8,9,50,1,2,3,4,5,6,7,8,9,60,1,2,3,4,5,6,7,8,9,70,1,2,3,4,5,6,7,8,9,80,1,2,3,4,5,6,7,8,9,90,1,2,3,4,5,6,7,8,9,100,1,2,3,4,5,6,7,8,9,110,1,2,3,4,5,6,7,8,9,120,1,2,3,4,5,6,7,8,9,130,1,2,3,4,5,6,7,8,9,140,1,2,3,4,5,6,7,8,9,150,1,2,3,4,5,6,7,8,9,160,1,2,3,4,5,6,7,8,9,170,1,2,3,4,5,6,7,8,9,180,1,2,3,4,5,6,7,8,9,190,1,2,3,4,5,6,7,8,9,200];
 // Lenght of arr1 is 200;
 let arr2 = [1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6,7,8,9,20,1,2,3,4,5,6,7,8,9,30,1,2,3,4,5,6,7,8,9,40,1,2,3,4,5,6,7,8,9,50,1,2,3,4,5,6,7,8,9,60,1,2,3,4,5,6,7,8,9,70,1,2,3,4,5,6,7,8,9,80,1,2,3,4,5,6,7,8,9,90,1,2,3,4,5,6,7,8,9,100];
 // Lenght of arr1 is 100;
```

**Let <mark>arr1</mark>** and **<mark>arr2</mark>** are two different arrays (as shown above) with lengths 200 and 100 respectively.

**<mark>arrResult</mark>** is an empty array to store the common elements in both the arrays after removing the duplicates.

### **Without using Sets:**

```javascript
arr1.filter(e=>arr2.includes(e) ? !arrResult.includes(e) ? arrResult.push(e):'':'')
console.log(arrResult);
```

*<mark>In this method, the browser takes 0.6000000238418579 milli seconds to execute the logic.</mark>*

### Using Sets

```javascript
let setArr1 = new Set(arr1); 
let setArr2 = new Set(arr2);
arrResult = [...setArr1.intersection(setArr2)]
console.log(arrResult);
```

*<mark>In this method, the browser takes 0.3999999761581421 milli seconds to execute the logic.</mark>*

### In this case, using sets is 66(+)% more performant than the previous method.
