JavaScript Set methods make one of the most common application problems—comparing two groups of values—read like the business rule they represent. Instead of converting sets to arrays and reaching for filter, teams can now use union, intersection, difference, symmetricDifference, isSubsetOf, isSupersetOf, and isDisjointFrom. The result is shorter code, fewer accidental mutations, and clearer permission, feature-flag, and data-reconciliation logic.
TL;DR
The modern Set API gives JavaScript native operations for combining, subtracting, and comparing unique collections. Use the non-mutating composition methods when producing a new result, and the predicate methods when a boolean is all you need. They are particularly useful at application boundaries: normalising IDs, checking access scopes, comparing selected filters, and reconciling records from different services.
Table of contents
- What are the new JavaScript Set methods?
- Which operation matches the product rule?
- How do Set methods make permission checks clearer?
- What should teams watch for in production?
- Where do these methods fit with arrays and iterators?
- FAQ
What are the new JavaScript Set methods?
A Set is JavaScript’s built-in collection for values that occur at most once. It has always been useful for de-duplicating IDs, but working with two sets used to be awkward. A simple “which permissions are both requested and granted?” check often became an array conversion, a callback, and a new Set.
The standard now defines three result-producing operations:
union(other)returns values found in either set.intersection(other)returns values found in both sets.difference(other)returns values in the first set but not the other.symmetricDifference(other)returns values found in exactly one set.
It also defines three questions:
isSubsetOf(other)checks whether every value in the first set is in the second.isSupersetOf(other)checks the reverse relationship.isDisjointFrom(other)checks whether the sets share no values.
These are specified in ECMAScript’s keyed-collections section, not added by a framework or utility package. The standard also deliberately accepts set-like objects, so the second argument can be another Set or an API-shaped collection with a numeric size, has, and keys methods. See the ECMAScript Set object specification and the original TC39 Set methods proposal for the contract.
const design = new Set(["figma", "tokens", "accessibility"]);
const engineering = new Set(["tokens", "typescript", "testing"]);
const shared = design.intersection(engineering);
// Set { "tokens" }
const combined = design.union(engineering);
// Set { "figma", "tokens", "accessibility", "typescript", "testing" }
const onlyEngineering = engineering.difference(design);
// Set { "typescript", "testing" }The receiver is never changed. That is a small but important property: engineering.difference(design) produces a new set, leaving engineering intact for the rest of the request or render. It makes state ownership easier to reason about than a helper that mutates a collection passed in from elsewhere.
Which operation matches the product rule?
Choosing the right operation is less about syntax and more about translating a product sentence faithfully.
- Product rule: Include anything a user selected or the system requires — Set method:
union— Example: filters + mandatory filters - Product rule: Include only options that both systems support — Set method:
intersection— Example: requested scopes ∩ granted scopes - Product rule: Remove things that were already processed — Set method:
difference— Example: pending IDs − completed IDs - Product rule: Find changes between two snapshots — Set method:
symmetricDifference— Example: old flags △ new flags - Product rule: Confirm all requested capabilities are allowed — Set method:
isSubsetOf— Example: requested ⊆ allowed - Product rule: Confirm a role covers a required baseline — Set method:
isSupersetOf— Example: role ⊇ minimum scopes - Product rule: Confirm an experiment cannot affect a segment — Set method:
isDisjointFrom— Example: excluded ∩ audience = ∅
That last group is often the bigger win. Before these predicates, a boolean test frequently built an intermediate array merely to call .every() or .some(). A direct predicate communicates intent and can stop as soon as the answer is known. The specification permits implementations to optimise based on collection size; application code should still treat the methods as semantic tools, rather than relying on a particular complexity guarantee.
For UI work, this is a useful companion to JavaScript iterator helpers: use iterators when transforming a sequence and a Set when uniqueness and membership are the important concepts. Converting back and forth without a reason is usually a signal that the model needs tightening.
How do Set methods make permission checks clearer?
Permissions are a good example because the wrong operation can create a subtle security bug. A request should be authorised only when every requested scope is part of the actor’s allowed scopes. That is a subset question, not an intersection question.
function canPerform(requestedScopes, allowedScopes) {
return new Set(requestedScopes).isSubsetOf(new Set(allowedScopes));
}
const requested = ["project:read", "billing:write"];
const allowed = ["project:read", "project:write", "billing:write"];
console.log(canPerform(requested, allowed)); // trueAn intersection would only tell us that some requested scope is allowed. That is a very different statement. Naming the relationship directly makes code review easier, especially when authorisation rules are spread across a frontend, API gateway, and service layer.
This does not replace server-side enforcement. Browser code is a convenience layer, and permissions must be checked again at the trusted boundary. But it gives client code a precise way to decide whether to show an action, preflight a request, or explain which scopes are missing:
const requested = new Set(["reports:read", "exports:create"]);
const allowed = new Set(["reports:read"]);
const missing = requested.difference(allowed);
// Set { "exports:create" }This approach also works well with the browser safeguards discussed in Trusted Types. Clear client-side capability handling reduces accidental exposure, while platform security controls constrain what untrusted content can do.
What should teams watch for in production?
First, target the runtimes you actually support. Set methods are part of the language specification, but an older embedded webview or frozen enterprise browser can lag behind. Check your project’s browser matrix and test the exact syntax in the oldest supported runtime. The MDN compatibility data for Set is a practical reference; the normative behaviour remains the ECMAScript specification.
Second, know how Set compares values. It uses SameValueZero: primitives compare by value, NaN matches NaN, and objects compare by identity. Two separately created objects with identical properties are not the same set member.
const fromApi = { id: "42" };
const fromCache = { id: "42" };
new Set([fromApi]).has(fromCache); // falseFor records, build sets from stable keys rather than objects:
const apiIds = new Set(apiUsers.map((user) => user.id));
const cachedIds = new Set(cachedUsers.map((user) => user.id));
const staleIds = cachedIds.difference(apiIds);Third, do not casually polyfill a security decision. If support for a legacy runtime matters, use a well-tested compatibility layer and add tests for the edge cases your policy depends on. For application-wide cancellation and time limits, the same principle applies: use the platform primitive deliberately, as in reliable AbortSignal.any() timeouts, rather than composing a fragile helper in every feature.
Finally, be deliberate about input size. A Set is excellent for membership and uniqueness, but it is not a substitute for pagination or a database query. If a browser would need to receive millions of IDs to calculate a difference, put that reconciliation next to the data instead.
Where do these methods fit with arrays and iterators?
Arrays preserve order and allow duplicates. Sets represent membership. Neither replaces the other.
Use an array when the order is visible to users, when repeated values matter, or when you need index-based operations. Use a set for selected IDs, feature keys, tags, scopes, and deduplicated observations. Convert at the boundary, not in every line of a pipeline:
const selectedIds = new Set(formData.getAll("teamMember"));
const activeIds = new Set(await fetchActiveMemberIds());
const validSelection = selectedIds.intersection(activeIds);
const payload = [...validSelection];This is also cleaner than using dynamically assembled regular expressions for membership-like tasks. When you genuinely do need a regex built from user-controlled text, use native RegExp.escape() rather than trying to turn a set problem into pattern matching.
A practical adoption checklist
- Search for helpers named
intersection,uniq,diff, orhasAllin your codebase. - Replace only the helpers whose inputs and outputs are genuinely sets of unique values.
- Keep arrays at presentation boundaries and turn them into sets close to membership logic.
- Add tests for empty sets, duplicate input,
NaNif relevant, and object identity. - Confirm the lowest supported browser or runtime has the methods—or ship a tested fallback.
- Prefer
isSubsetOfand friends for policy checks because reviewers can read the rule directly.
The payoff is modest per line but meaningful across a codebase: fewer hand-rolled utilities, clearer rules, and less accidental mutation. Modern JavaScript is increasingly good at expressing domain operations without making every team rebuild them from arrays.
FAQ
Do JavaScript Set methods mutate the original set?
No. union, intersection, difference, and symmetricDifference each return a new Set. The predicate methods return booleans. The original receiver and argument remain available unchanged.
When should I use intersection instead of isSubsetOf?
Use intersection when you need the shared values. Use isSubsetOf when you only need to know whether every value in one set is allowed or present in another; it expresses authorisation and validation rules more directly.
Can I pass an array as the second argument?
Not directly. The methods expect a set-like object, not just an iterable. Wrap the array with new Set(values) unless the object intentionally implements the required set-like API.
Are Set methods a replacement for database queries?
No. They are ideal for in-memory collections of reasonable size. Large reconciliation or filtering jobs should normally be done by the database or service that owns the data.