JavaScript Set Algebra: Union and Intersection
Quick answer
Set algebra combines membership across collections. Union includes either set, intersection includes both, difference includes only the receiver, and symmetric difference includes exactly one.
How it works
Modern Set methods union, intersection, difference and symmetricDifference return new sets. isSubsetOf, isSupersetOf and isDisjointFrom return booleans. These accept set-like arguments with size, has and keys; use real Sets for this lesson. Intersection may follow the smaller set’s order. Check support before relying on these methods; filtering an array against another Set is a portable alternative for membership.
const a=new Set([1,2]); const b=new Set([2,3]); console.log(JSON.stringify([...a.union(b)]), JSON.stringify([...a.intersection(b)]));Expected output in Node.js:
[1,2,3] [2]Union combines, intersection retains common membership. Tested in local Node.
const a=new Set([1,2]); const b=new Set([2,3]); console.log(JSON.stringify([...a.difference(b)]), a.isDisjointFrom(b));Expected output in Node.js:
[1] falseOnly 1 belongs solely to a; 2 is shared.
Common mistakes
Difference is directional: A minus B is not generally B minus A. Do not promise universal runtime support or assume intersection always uses receiver order.
Practice
Return the labels unique to the first list in first-occurrence order, using a Set and membership tests.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
JavaScript Set Algebra: Union and Intersection — Knowledge Check
Apply the taught concept and predict the output.
Which modern operation includes values in exactly one of two Sets?
What does isSubsetOf return?
Do Set algebra methods such as union mutate the receiver?
What is the exact console output in JavaScript Set Algebra: Union and Intersection example 1?
const a=new Set([1,2]); const b=new Set([2,3]); console.log(JSON.stringify([...a.union(b)]), JSON.stringify([...a.intersection(b)]));What is the exact console output in JavaScript Set Algebra: Union and Intersection example 2?
const a=new Set([1,2]); const b=new Set([2,3]); console.log(JSON.stringify([...a.difference(b)]), a.isDisjointFrom(b));