By the end of this lesson, you will be able to compute union, intersection, and difference between JavaScript Sets using spread syntax and has().
What it is
A Set stores unique values. Set logic combines or compares two sets: union contains every value from either set; intersection contains only values shared by both; difference contains values in the first set that are not in the second. Related terms: symmetric difference, subset, superset, and membership test with has().
Mental model: think of two boxes of unique items. Union dumps both boxes into a new box and removes duplicates. Intersection keeps only items that appear in both boxes. Difference keeps items from box A that are missing from box B.
Why it matters
- Remove duplicates when merging arrays or tags.
- Find common permissions, features, or user roles.
- Compute missing items, such as required fields not yet filled.
- Compare collections without nested loops.
- Build simple analytics, like users active in one campaign but not another.
Syntax or steps
The smallest useful pattern is to spread a Set into an array, then create a new Set from the result.
const union = new Set([...a, ...b]);
const intersection = new Set([...a].filter(x => b.has(x)));
const difference = new Set([...a].filter(x => !b.has(x)));
Steps: 1) convert one Set to an array with [...set]; 2) use filter() to keep or remove values; 3) pass the result to new Set() to remove duplicates and return a Set.
Example
const a = new Set([1, 2, 3, 4]);
const b = new Set([3, 4, 5, 6]);
const union = new Set([...a, ...b]);
const intersection = new Set([...a].filter(x => b.has(x)));
const difference = new Set([...a].filter(x => !b.has(x)));
const symmetricDifference = new Set([...union].filter(x => !intersection.has(x)));
console.log([...union]); // [1, 2, 3, 4, 5, 6]
console.log([...intersection]); // [3, 4]
console.log([...difference]); // [1, 2]
console.log([...symmetricDifference]); // [1, 2, 5, 6]
Part by part:
new Set([1, 2, 3, 4])creates a set of unique numbers.[...a, ...b]spreads both sets into one array, thennew Set()removes duplicates.[...a].filter(x => b.has(x))checks each value fromafor membership inb.!b.has(x)reverses the test to produce values only ina.console.log([...union])converts the result back to an array so the output is readable.
Common mistakes
- Using
includes()on a Set. Fix: usehas(). - Forgetting to spread before filtering. Fix: use
[...a].filter(...), nota.filter(...). - Assuming difference is symmetric. Fix:
aminusbis not the same asbminusa. - Expecting object values to match by shape. Fix: Sets compare by reference, so
{ id: 1 }and{ id: 1 }are different.
When to use it
Use Set logic when uniqueness and membership matter. Use array methods when order, duplicates, or index access matter.
| Task | Use Set logic | Use arrays |
|---|---|---|
| Merge unique tags | Yes | Only if duplicates are acceptable |
| Find shared IDs | Yes | Works, but slower for large data |
| Keep duplicate records | No | Yes |
| Sort by insertion order | Yes, Sets preserve insertion order | Yes |
Practice
Guided exercise: create two Sets of fruit names and compute the union.
const red = new Set(["apple", "cherry"]);
const yellow = new Set(["banana", "apple"]);
const allFruit = new Set([...red, ...yellow]);
console.log([...allFruit]);
Expected output: ["apple", "cherry", "banana"].
Challenge: write a function missing(required, provided) that returns required items not provided.
function missing(required, provided) {
return new Set([...required].filter(x => !provided.has(x)));
}
Solution hint: use difference logic with !provided.has(x).
Quick check
Question: If a = new Set([1, 2]) and b = new Set([2, 3]), what is [...new Set([...a].filter(x => !b.has(x)))]?
Answer: [1], because it keeps values in a that are not in b.
Summary
Set logic gives concise ways to combine and compare unique collections. In JavaScript, spread syntax plus has() and filter() lets you build union, intersection, and difference without mutating the original Sets.