JavaScript Sets

JavaScript Tutorial

JavaScript Sets

In JavaScript Sets is a collection of unique values. Unlike arrays, sets cannot contain duplicate elements. They are useful when you want to store only distinct values and perform operations like union, intersection, or difference efficiently.

 Creating a Set

Output:

Set(5) { 1, 2, 3, 4, 5 }

 Adding Values

Output:

Set(6) { 1, 2, 3, 4, 5, 6 }

 Checking Values

 Removing Values

Output:

Set(5) { 1, 2, 3, 5, 6 }

 Size of a Set

 Iterating Through a Set

Using for...of loop:

Using forEach():

 Converting Between Arrays and Sets

Array → Set

Set → Array

 Clearing a Set

 Key Points

  1. Stores unique values only

  2. Can store any type: numbers, strings, objects

  3. Maintains insertion order

  4. Provides fast operations: add, delete, has

Example: Practical Use

Remove duplicates from an array:


 

You may also like...