JavaScript Set Methods: Union and Intersection
Modern JavaScript has introduced native Set composition methods to ECMAScript, standardizing common mathematical set operations directly within the language. Previously, performing operations like finding the intersection or union of two sets required manual iteration, array conversions, or external utility libraries. These new built-in methods make set manipulation faster, more memory-efficient, and significantly easier to read and maintain.
The New Set Methods
The updated specification introduces seven core methods for set operations and comparisons:
1. union(other)
Returns a new set containing all unique elements present in either the original set, the argument set, or both.
const frontEnd = new Set(['HTML', 'CSS', 'JavaScript']);
const backEnd = new Set(['Node.js', 'Python', 'JavaScript']);
const fullStack = frontEnd.union(backEnd);
// Set(4) { 'HTML', 'CSS', 'JavaScript', 'Node.js', 'Python' }2. intersection(other)
Returns a new set containing only the elements that exist in both sets.
const teamA = new Set(['Alice', 'Bob', 'Charlie']);
const teamB = new Set(['Bob', 'David', 'Charlie']);
const commonMembers = teamA.intersection(teamB);
// Set(2) { 'Bob', 'Charlie' }3. difference(other)
Returns a new set containing elements that are in the first set but not in the second set.
const allUsers = new Set(['admin', 'editor', 'subscriber']);
const activeUsers = new Set(['editor', 'subscriber']);
const inactiveUsers = allUsers.difference(activeUsers);
// Set(1) { 'admin' }4.
symmetricDifference(other)
Returns a new set containing elements that are in either the first set or the second set, but not in both.
const packageA = new Set(['react', 'lodash']);
const packageB = new Set(['lodash', 'express']);
const uniquePackages = packageA.symmetricDifference(packageB);
// Set(2) { 'react', 'express' }Boolean Comparison Methods
In addition to producing new sets, JavaScript includes three predicate methods that return a boolean value based on the relationship between two sets:
isSubsetOf(other): Returnstrueif all elements of the calling set are included in the given set.isSupersetOf(other): Returnstrueif the calling set contains all elements of the given set.isDisjointFrom(other): Returnstrueif the calling set and the given set share no common elements.
const evens = new Set([2, 4, 6]);
const digits = new Set([1, 2, 3, 4, 5, 6, 7, 8, 9]);
const odds = new Set([1, 3, 5]);
evens.isSubsetOf(digits); // true
digits.isSupersetOf(evens); // true
evens.isDisjointFrom(odds); // trueWorking with Set-Like Objects
These methods do not strictly require the argument to be an instance
of Set. They accept any “Set-like” object—an object that
provides a .size property, a .has() method,
and a .keys() iterator. This allows seamless integration
with custom collections and data structures without explicit
conversions.