Episode 10 of 11
Sets
Learn the Set object — collections of unique values, common operations, and practical use cases.
Sets
A Set is a collection of unique values. Unlike arrays, sets automatically prevent duplicates. Values can be of any type — primitives or object references.
Creating a Set
// Empty set
const mySet = new Set();
// From an array
const colors = new Set(["red", "blue", "green", "red"]);
// Set(3) { "red", "blue", "green" } ← duplicate "red" removed!
// From a string
const letters = new Set("hello");
// Set(4) { "h", "e", "l", "o" } ← duplicate "l" removed!
Adding and Deleting Values
const fruits = new Set();
// add() — returns the Set (chainable)
fruits.add("apple");
fruits.add("banana");
fruits.add("cherry");
fruits.add("apple"); // Ignored — already exists!
console.log(fruits); // Set(3) { "apple", "banana", "cherry" }
// delete() — returns true if found
fruits.delete("banana"); // true
fruits.delete("grape"); // false (didn't exist)
// clear() — remove everything
fruits.clear();
console.log(fruits.size); // 0
Checking Values
const tags = new Set(["html", "css", "javascript"]);
tags.has("css"); // true
tags.has("python"); // false
// Size (not length!)
tags.size; // 3
Iterating Over a Set
const skills = new Set(["HTML", "CSS", "JavaScript"]);
// for...of
for (const skill of skills) {
console.log(skill);
}
// forEach
skills.forEach(skill => console.log(skill));
// Spread into array
const arr = [...skills];
// ["HTML", "CSS", "JavaScript"]
// Destructuring
const [first, second] = skills;
// first = "HTML", second = "CSS"
Sets maintain insertion order — you always iterate in the order items were added.
Remove Duplicates from an Array
const numbers = [1, 2, 3, 2, 4, 1, 5, 3];
// One-liner to remove duplicates:
const unique = [...new Set(numbers)];
// [1, 2, 3, 4, 5]
// Function version:
const removeDuplicates = arr => [...new Set(arr)];
This is the most common Set use case and one of the most famous ES6 patterns.
Set Operations
Union (all elements from both sets)
const a = new Set([1, 2, 3]);
const b = new Set([3, 4, 5]);
const union = new Set([...a, ...b]);
// Set(5) { 1, 2, 3, 4, 5 }
Intersection (elements in both sets)
const intersection = new Set([...a].filter(x => b.has(x)));
// Set(1) { 3 }
Difference (elements in A but not B)
const difference = new Set([...a].filter(x => !b.has(x)));
// Set(2) { 1, 2 }
Set vs Array
| Feature | Array | Set |
|---|---|---|
| Duplicates | Allowed | Automatically removed |
| Access by index | arr[0] ✅ | Not supported ❌ |
| Check existence | arr.includes() — O(n) | set.has() — O(1) 🚀 |
| Size | arr.length | set.size |
| Order | Insertion order | Insertion order |
| Methods | map, filter, reduce… | add, delete, has, clear |
Practical Example: Tracking Unique Visitors
const visitors = new Set();
function trackVisitor(userId) {
visitors.add(userId);
console.log(`Unique visitors: ${visitors.size}`);
}
trackVisitor("user_123"); // Unique visitors: 1
trackVisitor("user_456"); // Unique visitors: 2
trackVisitor("user_123"); // Unique visitors: 2 ← already tracked!
Key Takeaways
- Sets store unique values only — duplicates are automatically ignored
set.has()is O(1) — much faster thanarray.includes()for large collections[...new Set(array)]is the ES6 one-liner to remove duplicates- Sets maintain insertion order and are iterable
- Combine with spread and filter for union, intersection, and difference operations