JavaScript Sets
JavaScript Sets
A Set in JavaScript 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:
🔹 Adding Values
Output:
🔹 Checking Values
🔹 Removing Values
Output:
🔹 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
-
Stores unique values only
-
Can store any type: numbers, strings, objects
-
Maintains insertion order
-
Provides fast operations:
add,delete,has
Example: Practical Use
Remove duplicates from an array:
