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:

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:


 

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *