If you have studied sets in mathematics, you know union, intersection and difference. For years, JavaScript’s Set could store unique values but could not do any of these operations, so everyone wrote their own helpers. Modern JavaScript now has them built in: seven new methods that combine and compare sets. They are supported in all major browsers since 2024 and in Node.js 22.
In this lesson you will learn
union,intersection,differenceandsymmetricDifferenceisSubsetOf,isSupersetOfandisDisjointFrom- Which methods return new sets and which return true or false
- Using “set-like” objects such as a
Mapas the argument - Working with arrays by converting them to sets
You should know Map and Set and arrays.
Combining Sets
const science = new Set(["Rafi", "Nadia", "Tanvir", "Mitu"]);
const sports = new Set(["Tanvir", "Lima", "Rafi", "Sakib"]);
const show = (label, s) => console.log(label.padEnd(22), [...s].join(", "));
show("union", science.union(sports)); // in either club
show("intersection", science.intersection(sports)); // in both clubs
show("difference", science.difference(sports)); // science only
show("symmetricDifference", science.symmetricDifference(sports)); // exactly one club
// The original sets are not changed: each method returns a new Set
show("science is still", science);
Output
union Rafi, Nadia, Tanvir, Mitu, Lima, Sakib
intersection Rafi, Tanvir
difference Nadia, Mitu
symmetricDifference Nadia, Mitu, Lima, Sakib
science is still Rafi, Nadia, Tanvir, Mitu
a.union(b)has everything in either set: every student in at least one club.a.intersection(b)keeps only values in both: Rafi and Tanvir are in both clubs.a.difference(b)keeps values inathat are not inb. Order matters:sports.difference(science)would give Lima and Sakib.a.symmetricDifference(b)keeps values in exactly one of the sets.- All four return a new Set. The originals are unchanged, which is safer than editing them.
Comparing Sets
const required = new Set(["html", "css", "javascript"]);
const rafiSkills = new Set(["html", "css", "javascript", "python"]);
const mituSkills = new Set(["html", "figma"]);
// Comparison methods return true or false
console.log(required.isSubsetOf(rafiSkills)); // every required skill is in Rafi's set
console.log(rafiSkills.isSupersetOf(required)); // the same check from the other side
console.log(required.isSubsetOf(mituSkills));
console.log(mituSkills.isDisjointFrom(new Set(["sql", "java"]))); // nothing in common
// What is Mitu missing?
console.log("Mitu should learn:", [...required.difference(mituSkills)]);
// The argument can be any "set-like" object: it needs size, has() and keys()
const allowed = new Map([["admin", 1], ["editor", 2]]);
const roles = new Set(["editor", "guest", "admin"]);
console.log("Unknown roles:", [...roles.difference(allowed)]);
// Arrays are not set-like, so wrap them in a Set first
const tags = ["js", "css", "js", "html", "css"];
console.log(new Set(tags).intersection(new Set(["css", "react"])));
try {
roles.union(["x"]);
} catch (e) {
console.log(e.name + ":", e.message);
}
Output
true
true
false
true
Mitu should learn: [ 'css', 'javascript' ]
Unknown roles: [ 'guest' ]
Set(1) { 'css' }
TypeError: The .size property is NaN
required.isSubsetOf(rafiSkills)asks “is every required skill in Rafi’s set?”isSupersetOfasks the same question from the other side.isDisjointFromistruewhen the two sets have nothing in common.differenceanswers practical questions like “which skills is Mitu missing?”- The argument does not have to be a Set. Any set-like object works if it has a
sizeproperty andhas()andkeys()methods. AMapqualifies, and its keys are used. - Arrays are not set-like, because they have
length, notsize. Passing one throws aTypeError, so wrap it withnew Set(array)first. (The exact error message differs between browsers.)
| Method | Returns | Maths name |
|---|---|---|
a.union(b) | New Set | A ∪ B |
a.intersection(b) | New Set | A ∩ B |
a.difference(b) | New Set | A − B |
a.symmetricDifference(b) | New Set | A Δ B |
a.isSubsetOf(b) | Boolean | A ⊆ B |
a.isSupersetOf(b) | Boolean | A ⊇ B |
a.isDisjointFrom(b) | Boolean | A ∩ B = ∅ |
Common Mistakes
- Passing an array as the argument. Convert it with
new Set(arr). - Expecting the original set to change. Save the returned set:
a = a.union(b). - Mixing up the order of
difference, which gives a different answer when the sets are swapped. - Comparing objects by content. Sets compare objects by reference, so two different
{ id: 1 }objects are both kept. Use IDs or strings as the values.
Practice Exercises
Exercise 1. Two friends list the films they have seen. Find the films only one of them has seen.
Show answer
const nadia = new Set(["Hawa", "Aynabaji", "Monpura"]);
const tanvir = new Set(["Aynabaji", "Television", "Monpura"]);
console.log([...nadia.symmetricDifference(tanvir)]); // ["Hawa", "Television"]
Exercise 2. Check whether an order only contains products that are in stock.
Show answer
const inStock = new Set(["rice", "dal", "oil", "salt"]);
const order = new Set(["rice", "oil"]);
console.log(order.isSubsetOf(inStock)); // true
Frequently Asked Questions
What did people use before these methods existed?
Short helpers built from spread and filter, such as new Set([...a].filter(x => b.has(x))) for an intersection. You will still see this pattern in older code, and it remains a good fallback for very old browsers.
In what order are the values in the result?
Mostly in the order of the first set, followed by new values from the second for union. For intersection, the engine may loop over the smaller set, so the order can follow that set instead. Do not rely on the order; sort the result if it matters.
Summary
union,intersection,differenceandsymmetricDifferencereturn new sets.isSubsetOf,isSupersetOfandisDisjointFromreturn true or false.- The argument can be any set-like object, such as a Set or a Map, but not an array.
- The original sets are never changed.
