Sub topic 7
Comparing Sets: isSubsetOf, isSupersetOf, isDisjointFrom
The earlier chapters covered methods that build a new Set: union, intersection, difference, and symmetricDifference. Often you don't need a new collection. You need a yes-or-no answer. Does this user have every permission the page requires? Do two tag lists share anything? Is one list of IDs fully contained in another?
ES2025 adds three predicate methods for these questions. A predicate is a function that returns true or false. These three return a boolean, build no new Set, and stop as soon as they know the answer.
This chapter assumes you can create and iterate a Set and that you know Set elements are compared with SameValueZero. That is the same rule has uses, where NaN matches NaN and +0 matches -0. It also assumes you have seen intersection and difference. All three predicates are shortcuts for questions you could answer with those methods.
The Three Questions
Each predicate is called on one set (the receiver) and takes another set as its argument:
a.isSubsetOf(b)asks whether every element ofais also inb.a.isSupersetOf(b)asks whether every element ofbis also ina.a.isDisjointFrom(b)asks whetheraandbhave no elements in common.
const required = new Set(["read", "write"]);
const granted = new Set(["read", "write", "delete"]);
const banned = new Set(["admin"]);
console.log(required.isSubsetOf(granted)); // true
console.log(granted.isSupersetOf(required)); // true
console.log(granted.isDisjointFrom(banned)); // true
console.log(granted.isSubsetOf(required)); // false ("delete" is missing from required)
console.log(required.isDisjointFrom(granted)); // false (they share "read" and "write")isSubsetOf and isSupersetOf mirror each other. a.isSubsetOf(b) always gives the same answer as b.isSupersetOf(a). isDisjointFrom is symmetric, so a.isDisjointFrom(b) equals b.isDisjointFrom(a).
How They Relate to the Set-Building Methods
Each predicate matches a check you could write with the methods from earlier chapters. The predicate version is shorter and usually faster, because it doesn't allocate a new Set and it can return at the first counterexample.
| Predicate | Equivalent long form | Returns `true` when |
|---|---|---|
| `a.isSubsetOf(b)` | `a.difference(b).size === 0` | nothing in `a` is missing from `b` |
| `a.isSupersetOf(b)` | `b.difference(a).size === 0` | nothing in `b` is missing from `a` |
| `a.isDisjointFrom(b)` | `a.intersection(b).size === 0` | `a` and `b` share no element |
const a = new Set([1, 2]);
const b = new Set([1, 2, 3]);
console.log(a.isSubsetOf(b), a.difference(b).size === 0); // true true
console.log(a.isSupersetOf(b), b.difference(a).size === 0); // false false
console.log(a.isDisjointFrom(b), a.intersection(b).size === 0); // false falseThe table also helps you remember the direction. A subset check is a difference check, so the receiver is the side that must have no leftovers.
Edge Cases Worth Memorizing
These methods follow the mathematical definitions, and the edge cases come straight from those definitions.
A set is a subset of itself
"Subset" here means non-strict subset. Every element of a is in a, so a.isSubsetOf(a) is true. The same holds for supersets.
The empty set
The empty set has no element that could be missing from another set. It is therefore a subset of every set and disjoint from every set, including itself.
const empty = new Set();
const s = new Set([1, 2]);
console.log(empty.isSubsetOf(s)); // true
console.log(s.isSupersetOf(empty)); // true
console.log(empty.isDisjointFrom(s)); // true
console.log(empty.isDisjointFrom(empty)); // true
console.log(empty.isSubsetOf(empty)); // trueSameValueZero still applies
The predicates use the same comparison as has. NaN matches NaN, and 0 matches -0. Objects match only when they are the same reference. A later chapter covers that last point in detail.
console.log(new Set([NaN]).isSubsetOf(new Set([NaN, 1]))); // true
console.log(new Set([-0]).isDisjointFrom(new Set([0]))); // false
console.log(new Set([{ id: 1 }]).isSubsetOf(new Set([{ id: 1 }]))); // false (different objects)Building Equality and Strict Subset Checks
JavaScript has no Set.prototype.equals, and === compares references, not contents. You can build both missing checks from the predicates.
function setsEqual(a, b) {
return a.size === b.size && a.isSubsetOf(b);
}
function isProperSubset(a, b) {
return a.size < b.size && a.isSubsetOf(b);
}
const x = new Set([1, 2, 3]);
const y = new Set([3, 2, 1]);
const z = new Set([1, 2]);
console.log(x === y); // false (different objects)
console.log(setsEqual(x, y)); // true (order does not matter)
console.log(isProperSubset(z, x)); // true
console.log(isProperSubset(x, y)); // false (equal sets are not proper subsets)The setsEqual check is correct because Sets cannot contain duplicates. If a and b have the same size and every element of a is in b, then b has no room for anything else. Insertion order is ignored, so [1, 2, 3] and [3, 2, 1] count as equal.
How Each Predicate Does Its Work
The specification describes exactly what each method reads from its argument. The details matter for performance, and they also matter when you pass a Map or a custom set-like object instead of a real Set.
Every predicate first reads the argument's size, has, and keys, the set-like protocol covered in a later chapter. Then it compares sizes. If the sizes alone settle the answer, the method returns without looking at any elements.
| Method | Returns `false` immediately when | Then iterates | Calls on the argument |
|---|---|---|---|
| `a.isSubsetOf(b)` | `a.size > b.size` | elements of `a` | `has` |
| `a.isSupersetOf(b)` | `a.size < b.size` | `b.keys()` | `keys` |
| `a.isDisjointFrom(b)` | never by size alone | the smaller side | `has` if `a` is smaller or equal, else `keys` |
isDisjointFrom chooses which side to loop over. If a.size <= b.size, it walks a and calls b.has. Otherwise it walks b.keys() and checks each key against a. Either way the loop runs over the smaller collection, and it stops at the first shared element.
Watching the shortcuts happen
A custom set-like object lets you see which members get used. The object below stands for "all numbers". Its size is Infinity, which the protocol allows, and its has checks the type. Its keys throws, because an infinite set cannot be listed.
const allNumbers = {
size: Infinity,
has(value) {
return typeof value === "number";
},
keys() {
throw new Error("cannot list every number");
},
};
const ids = new Set([1, 2, 3]);
console.log(ids.isSubsetOf(allNumbers)); // true (only has is called)
console.log(ids.isDisjointFrom(allNumbers)); // false (ids is smaller, so has is called)
console.log(ids.isSupersetOf(allNumbers)); // false (3 < Infinity, so keys is never called)
console.log(new Set(["x"]).isSubsetOf(allNumbers)); // falseNone of these calls throws. Each method returns before it needs keys, either because of the size check or because it only needs has.
Passing a Map or an array
Any argument with a numeric size plus callable has and keys methods works. A Map qualifies, and its keys act as the elements. An array has no size property, so it throws a TypeError.
const needed = new Set(["b", "c"]);
const stock = new Map([["a", 5], ["b", 1], ["c", 0]]);
console.log(needed.isSubsetOf(stock)); // true (compares against the Map's keys)
try {
needed.isSubsetOf(["b", "c"]);
} catch (err) {
console.log(err instanceof TypeError); // true
}
console.log(needed.isSubsetOf(new Set(["b", "c"]))); // true (wrap arrays first)The Map example compares keys only. "c" maps to 0, but it still counts as present. If "in stock" should mean a count above zero, filter the Map before comparing.
Common Mistakes
- Reversing the direction.
required.isSubsetOf(granted)andgranted.isSubsetOf(required)answer different questions. Read the call aloud: "required is a subset of granted." - Using a predicate where you need the elements. A predicate says whether something is missing, not what is missing. For an error message such as "missing permission: write", use
required.difference(granted). - Treating
isSubsetOfas strict. Equal sets pass. Add asizecomparison when you need a proper subset. - Expecting content equality for objects. Two objects with the same contents are still different elements. Compare by a primitive key such as an ID instead.
- Passing arrays. Wrap them with
new Set(array).
Here is a permission check that reports what is missing and uses the predicate as the fast path:
function checkAccess(required, granted) {
if (required.size === 0) {
return { ok: false, missing: [], reason: "no requirements configured" };
}
if (required.isSubsetOf(granted)) {
return { ok: true, missing: [] };
}
return { ok: false, missing: [...required.difference(granted)] };
}
const granted = new Set(["read", "comment"]);
console.log(checkAccess(new Set(["read"]), granted));
// { ok: true, missing: [] }
console.log(checkAccess(new Set(["read", "write", "delete"]), granted));
// { ok: false, missing: ["write", "delete"] }
console.log(checkAccess(new Set(), granted));
// { ok: false, missing: [], reason: "no requirements configured" }Exercises
Exercise
Given a = new Set([1, 2]), b = new Set([2, 1]), and e = new Set(), what do a.isSubsetOf(b), a.isSupersetOf(b), e.isDisjointFrom(e), and a.isDisjointFrom(e) return?
Show answer
All four return true. a and b have the same elements, so each is a subset and a superset of the other, and order is ignored. The empty set shares no element with any set, including itself, so both disjoint checks are true.
Exercise
Write a function sameTags(a, b) that returns true only when two Sets contain exactly the same elements, without using the spread operator or loops.
Show answer
function sameTags(a, b) { return a.size === b.size && a.isSubsetOf(b); } A Set cannot contain duplicates. If both sets have the same size and every element of a is in b, then b holds nothing else.
Exercise
A custom set-like object has size 2, a has method that logs each call and returns true, and a keys method that throws. Which of these call has, which call keys, and which return without either: new Set([1, 2, 3]).isSubsetOf(obj), new Set([1]).isSupersetOf(obj), new Set([1]).isDisjointFrom(obj)?
Show answer
isSubsetOf returns false without calling has or keys, because 3 > 2. isSupersetOf returns false without calling either, because 1 < 2. isDisjointFrom calls has, because the receiver's size of 1 is less than or equal to 2, so it walks the receiver. has(1) returns true, so the result is false, and keys is never called.
Exercise
A config loader returns new Set() when the "requiredRoles" key is misspelled. Why does requiredRoles.isSubsetOf(userRoles) then grant access, and how do you fix it?
Show answer
The empty set is a subset of every set, so the check returns true for any user. Treat an empty requirement set as a configuration error: check requiredRoles.size === 0 and deny access or throw before calling isSubsetOf.