JS Tutorial



JS SETS


JavaScript Sets 🛠️

In JavaScript, a Set is a collection of unique values. Unlike arrays, sets do not allow duplicate elements, which makes them useful when you need to store distinct values.

💡 Creating a Set

You can create a Set using the Set constructor. Here is an example:

// Creating a Set with values
let numbers = new Set([1, 2, 3, 4, 5]);

// Display the Set
console.log(numbers);  // Set { 1, 2, 3, 4, 5 }
  

🔎 Properties and Methods

Here are some important properties and methods of a Set:

  • add(value): Adds a value to the Set
  • delete(value): Removes a value from the Set
  • has(value): Checks if a value exists in the Set
  • size: Returns the number of elements in the Set
  • clear(): Removes all values from the Set
// Methods and properties in action
let fruits = new Set();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Cherry");
fruits.add("Apple");  // Duplicate, will be ignored

console.log(fruits.size);  // 3
console.log(fruits.has("Banana"));  // true
console.log(fruits.has("Mango"));  // false

fruits.delete("Banana");
console.log(fruits);  // Set { "Apple", "Cherry" }

fruits.clear();
console.log(fruits);  // Set {}
  

🧑‍🏫 Live Example: Set Operations

Set Result will be shown here

📌 Use Cases of Sets

  • Storing unique items (like a list of user IDs)
  • Eliminating duplicates from arrays
  • Efficient membership checking (e.g., checking if an element exists)
  • Working with mathematical operations on sets (union, intersection, etc.)

⚡ Advanced Set Operations

Sets can be used for more advanced operations like finding the union or intersection of two sets. Here's a brief example:

// Union of two sets
let setA = new Set([1, 2, 3]);
let setB = new Set([3, 4, 5]);

let union = new Set([...setA, ...setB]);
console.log(union);  // Set { 1, 2, 3, 4, 5 }

// Intersection of two sets
let intersection = new Set([...setA].filter(x => setB.has(x)));
console.log(intersection);  // Set { 3 }
  
Note: Sets are especially useful when you need to perform operations on unique values efficiently, such as checking for duplicates or performing set algebra.

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review