Why This Matters
Sometimes you need to answer a simple question: "Have I seen this before?" With an array, answering that question means scanning every element — slow for large collections. A set gives you that answer instantly. Sets store unique values only and provide O(1) membership testing, built on the same hash function technology as hash maps.
Sets are the right tool whenever you need to track unique items, eliminate duplicates, or compute relationships between groups (union, intersection, difference). They appear constantly in real-world code — from deduplicating database results to finding common friends in a social network.
Define Terms
Visual Model
The full process at a glance. Click Start tour to walk through each step.
Sets store unique elements with O(1) membership testing. Built on hash tables.
Code Example
// Creating a set
const fruits = new Set(["apple", "banana", "cherry"]);
fruits.add("date");
fruits.add("apple"); // ignored — already exists!
console.log(fruits.size); // 4
console.log(fruits.has("banana")); // true (O(1) lookup)
// Deduplication — the most common set pattern
const numbers = [1, 3, 5, 3, 1, 7, 5, 9, 7];
const unique = [...new Set(numbers)];
console.log(unique); // [1, 3, 5, 7, 9]
// Set operations
const a = new Set([1, 2, 3, 4]);
const b = new Set([3, 4, 5, 6]);
// Union: all elements from both
const union = new Set([...a, ...b]);
console.log([...union]); // [1, 2, 3, 4, 5, 6]
// Intersection: elements in both
const intersection = new Set([...a].filter(x => b.has(x)));
console.log([...intersection]); // [3, 4]
// Difference: elements in a but not b
const difference = new Set([...a].filter(x => !b.has(x)));
console.log([...difference]); // [1, 2]Interactive Experiment
Try these exercises:
- Create a set from the string
"mississippi". What unique characters does it contain? - Given two arrays of friend IDs, use sets to find mutual friends (intersection).
- Add the same value to a set three times. What is the set's size afterward?
- Time the difference between checking if a value exists in a set vs. an array of 10,000 elements. How much faster is the set?
Quick Quiz
Coding Challenge
Write a function called `intersection` that takes two arrays and returns a new array containing only the elements present in both arrays. The result should contain no duplicates. Use sets for an efficient solution.
Real-World Usage
Sets appear frequently in production software:
- Deduplication: Remove duplicate emails, IDs, or records before processing
- Permission systems: Store user roles as a set; check membership to authorize actions
- Social networks: Find mutual friends (intersection), suggest friends-of-friends (difference)
- Search engines: Intersect sets of document IDs matching different search terms
- Feature flags: Track which features are enabled for a user as a set of strings
- Visited tracking: In web crawlers and graph algorithms, track visited nodes in a set