JavaScript Sets
8 April 2025 | Category: JavaScript
A Set is a built-in JavaScript object that lets you store unique values — no duplicates allowed!
Sets are useful when you need a collection of values where order doesn’t matter and no repetitions are allowed.
✅ Key Features of Sets
- No duplicate values
- Insertion order is preserved
- Values can be of any type: string, number, object, etc.
🧱 Creating a Set
You create a Set using the Set
constructor:
const letters = new Set();
You can also pass an array to initialize it with values:
const numbers = new Set([1, 2, 3, 4]);
➕ Adding Values
Use .add()
to add items to a Set:
const fruits = new Set();
fruits.add("apple");
fruits.add("banana");
fruits.add("apple"); // duplicate, won't be added
console.log(fruits);
Output:
Set(2) { "apple", "banana" }
➖ Removing Values
✅ delete()
fruits.delete("banana");
✅ clear()
fruits.clear(); // removes all values
❓ Checking Values
✅ has()
console.log(fruits.has("apple")); // true
console.log(fruits.has("mango")); // false
🔁 Looping Through a Set
Use for...of
or forEach()
:
for (let fruit of fruits) {
console.log(fruit);
}
OR
fruits.forEach(fruit => {
console.log(fruit);
});
🧮 Set Size
Use .size
to get the number of elements:
console.log(fruits.size); // 2
🧪 Example: Remove Duplicates from Array
const arr = [1, 2, 3, 2, 1, 4];
const unique = [...new Set(arr)];
console.log(unique); // [1, 2, 3, 4]
🔹 Very handy for filtering out repeated values!
🧾 Summary
Method | Description |
---|---|
add(value) | Adds a value |
delete(value) | Removes a specific value |
has(value) | Checks if value exists |
clear() | Removes all values |
size | Returns number of values |
🧠 When to Use a Set?
- Removing duplicates from arrays
- Storing a list of unique items (like tags, selected values, etc.)
- Fast lookup without caring about order