Reading history

JavaScript Set Methods: union, intersection and more

5 min read 1 views

Learn the new JavaScript Set methods: union, intersection, difference, symmetricDifference, isSubsetOf, isSupersetOf and isDisjointFrom.

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, difference and symmetricDifference
  • isSubsetOf, isSupersetOf and isDisjointFrom
  • Which methods return new sets and which return true or false
  • Using “set-like” objects such as a Map as 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
ABA.union(B)ABA.intersection(B)ABA.difference(B)ABA.symmetricDifference(B)
  • 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 in a that are not in b. 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?” isSupersetOf asks the same question from the other side.
  • isDisjointFrom is true when the two sets have nothing in common.
  • difference answers 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 size property and has() and keys() methods. A Map qualifies, and its keys are used.
  • Arrays are not set-like, because they have length, not size. Passing one throws a TypeError, so wrap it with new Set(array) first. (The exact error message differs between browsers.)
MethodReturnsMaths name
a.union(b)New SetA ∪ B
a.intersection(b)New SetA ∩ B
a.difference(b)New SetA − B
a.symmetricDifference(b)New SetA Δ B
a.isSubsetOf(b)BooleanA ⊆ B
a.isSupersetOf(b)BooleanA ⊇ B
a.isDisjointFrom(b)BooleanA ∩ B = ∅

Common Mistakes

  1. Passing an array as the argument. Convert it with new Set(arr).
  2. Expecting the original set to change. Save the returned set: a = a.union(b).
  3. Mixing up the order of difference, which gives a different answer when the sets are swapped.
  4. 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, difference and symmetricDifference return new sets.
  • isSubsetOf, isSupersetOf and isDisjointFrom return 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.

Next: JavaScript Custom Events and EventTarget.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *