Sub topic 8
Union, Intersection, Difference, and Subset Checks
This chapter assumes you already know how to create a Set, add and check values with add and has, and iterate a Set in insertion order. It also assumes you know SameValueZero equality from earlier chapters, because every method here uses it to decide whether two values match.
For years, combining two Sets in JavaScript meant spreading them into arrays and filtering by hand. ES2025 added seven built-in methods to Set.prototype for this. Four of them build a new Set, and three of them answer a yes-or-no question about how two Sets relate.
The Seven Methods at a Glance
| Method | Returns | Contains or answers |
|---|---|---|
| `a.union(b)` | new Set | Every value in `a` or `b` |
| `a.intersection(b)` | new Set | Values in both `a` and `b` |
| `a.difference(b)` | new Set | Values in `a` but not in `b` |
| `a.symmetricDifference(b)` | new Set | Values in exactly one of the two |
| `a.isSubsetOf(b)` | boolean | Is every value of `a` also in `b`? |
| `a.isSupersetOf(b)` | boolean | Is every value of `b` also in `a`? |
| `a.isDisjointFrom(b)` | boolean | Do `a` and `b` share no values? |
None of these methods modify a or b. The four that return Sets always return a fresh Set instance.
Building New Sets
const a = new Set([1, 2, 3]);
const b = new Set([2, 3, 4]);
console.log(a.union(b)); // Set {1, 2, 3, 4}
console.log(a.intersection(b)); // Set {2, 3}
console.log(a.difference(b)); // Set {1}
console.log(a.symmetricDifference(b)); // Set {1, 4}
console.log(a); // Set {1, 2, 3} (unchanged)
console.log(b); // Set {2, 3, 4} (unchanged)Order matters for difference. a.difference(b) is {1}, and b.difference(a) is {4}. The other three set-producing operations give the same members whichever Set you call them on, though the iteration order can differ.
Result Order
Sets iterate in insertion order, so the order of the result is something you can see. For union, the result lists the values of this first, followed by the values of the argument that were not already present:
const first = new Set(['c', 'a']);
const second = new Set(['b', 'a', 'd']);
console.log([...first.union(second)]); // ['c', 'a', 'b', 'd']
console.log([...second.union(first)]); // ['b', 'a', 'd', 'c']intersection is less predictable. The specification walks whichever Set is smaller, for speed. When this is larger than the argument, the result follows the argument's order instead of the order of this.
const big = new Set([5, 4, 3, 2, 1]);
const small = new Set([1, 3]);
console.log([...big.intersection(small)]); // [1, 3] (follows small)
console.log([...small.intersection(big)]); // [1, 3]Asking Questions About Two Sets
const a = new Set([1, 2, 3]);
console.log(a.isSubsetOf(new Set([1, 2, 3, 4]))); // true
console.log(a.isSupersetOf(new Set([2, 3]))); // true
console.log(a.isDisjointFrom(new Set([7, 8]))); // true
console.log(a.isDisjointFrom(new Set([3, 9]))); // false
const empty = new Set();
console.log(empty.isSubsetOf(a)); // true
console.log(a.isSubsetOf(a)); // trueTwo edge cases surprise people. The empty Set is a subset of every Set, because it has no value that fails the check. Every Set is also a subset of itself, so isSubsetOf means "subset or equal". JavaScript has no built-in Set equality method, but you can build one from these checks:
function setsEqual(x, y) {
return x.size === y.size && x.isSubsetOf(y);
}
console.log(setsEqual(new Set([1, 2]), new Set([2, 1]))); // true
console.log(setsEqual(new Set([1, 2]), new Set([1, 3]))); // falseA Practical Example: Permissions
Set methods are useful when you compare groups of tags, roles, or IDs. Here a user's granted permissions are checked against what an action requires:
const granted = new Set(['read', 'write', 'comment']);
const required = new Set(['read', 'delete']);
if (required.isSubsetOf(granted)) {
console.log('Allowed');
} else {
const missing = required.difference(granted);
console.log('Missing:', [...missing]); // Missing: ['delete']
}
const revoked = new Set(['comment']);
const effective = granted.difference(revoked);
console.log([...effective]); // ['read', 'write']The Argument Must Be Set-Like
The argument does not need to be a Set. It must be set-like, which means it provides three things:
- a numeric
sizeproperty, - a
has(value)method, - a
keys()method that returns an iterator.
The methods read size first. If size converts to NaN, they throw a TypeError. If it is negative, they throw a RangeError. If has or keys is not a function, they throw a TypeError. Arrays have no size property, so passing an array is the most common mistake:
const tags = new Set(['js', 'css']);
try {
tags.union(['html']);
} catch (err) {
console.log(err instanceof TypeError); // true
}
console.log([...tags.union(new Set(['html']))]); // ['js', 'css', 'html']A Map is set-like because it has size, has, and keys. The methods treat it as the set of its keys and ignore its values:
const stock = new Map([['apple', 5], ['pear', 0]]);
const wanted = new Set(['apple', 'kiwi']);
console.log([...wanted.intersection(stock)]); // ['apple']
console.log([...wanted.difference(stock)]); // ['kiwi']Gotcha: Which Method Gets Called
Each method uses only what it needs from the argument. Some methods call has, some call keys, and some switch between them depending on the sizes. This lets you pass a set-like object that describes an infinite set, as long as the method you call never needs to enumerate it:
const evens = {
size: Infinity,
has: (n) => n % 2 === 0,
keys() {
throw new Error('Cannot list every even number');
}
};
const nums = new Set([2, 4, 6]);
console.log(nums.isSubsetOf(evens)); // true
console.log([...new Set([1, 2, 3]).intersection(evens)]); // [2]
try {
nums.union(evens); // union must enumerate the argument
} catch (err) {
console.log(err.message); // Cannot list every even number
}isSubsetOf and intersection only call evens.has here, because this is the smaller collection. union always iterates the argument, so it calls keys() and fails.
Support and Fallbacks
These methods are in Chrome and Edge 122+, Firefox 127+, Safari 17+, and Node.js 22+. For older runtimes, check before using them, or write small helpers:
function union(x, y) {
return new Set([...x, ...y]);
}
function intersection(x, y) {
return new Set([...x].filter((v) => y.has(v)));
}
function difference(x, y) {
return new Set([...x].filter((v) => !y.has(v)));
}
const hasNative = typeof Set.prototype.union === 'function';
const p = new Set([1, 2]);
const q = new Set([2, 3]);
const u = hasNative ? p.union(q) : union(p, q);
console.log([...u]); // [1, 2, 3]
console.log([...intersection(p, q)]); // [2]
console.log([...difference(p, q)]); // [1]The helpers always keep the order of x, which the native intersection does not promise. They also do not validate their argument the way the native methods do.
Common Errors
| Mistake | What happens | Fix |
|---|---|---|
| Passing an array | `TypeError` (no `size`) | Wrap it: `new Set(arr)` |
| Expecting `a` to change | `a` is unchanged | Assign the result: `a = a.union(b)` |
| Confusing `a.difference(b)` with `b.difference(a)` | Wrong values | Read it as "a minus b" |
| Comparing object values by content | No matches | Compare IDs, or keep shared references |
| Relying on intersection order | Order follows the smaller Set | Sort or filter explicitly |
Exercise
Given const a = new Set([1, 2, 3]) and const b = new Set([3, 4]), what do a.symmetricDifference(b), b.difference(a), and a.isDisjointFrom(b) return?
Show answer
a.symmetricDifference(b) is Set {1, 2, 4}, b.difference(a) is Set {4}, and a.isDisjointFrom(b) is false because both Sets contain 3.
Exercise
Why does new Set(['x']).isSubsetOf(['x', 'y']) throw, and what two ways can you fix it?
Show answer
An array is not set-like. It has no size property, so size converts to NaN and the method throws a TypeError. You can wrap the array in a Set, as in isSubsetOf(new Set(['x', 'y'])), or pass any object that has a numeric size, a has method, and a keys method.
Exercise
A Map named prices has keys 'tea' and 'milk'. What does new Set(['tea', 'sugar']).difference(prices) return, and why?
Show answer
It returns Set {'sugar'}. A Map is set-like, so the method uses the Map's keys and ignores its values. 'tea' is a key in the Map, so it is removed, and 'sugar' remains.