
Loading...
Loading...

The JavaScript Set object is more than a collection of unique values. New ergonomic methods let you work with sets like a proper algebraic data structure.
example: unionconst evens = new Set([2, 4, 6, 8]);
const squares = new Set([1, 4, 9]);
console.log(evens.union(squares)); // Set(6) { 2, 4, 6, 8, 1, 9 }
The union() method combines two sets and keeps only unique values. This is handy when you want a merged collection without duplicates.
const odds = new Set([1, 3, 5, 7, 9]);
const squares = new Set([1, 4, 9]);
console.log(odds.intersection(squares)); // Set(2) { 1, 9 }
intersection() returns a new set containing only values that exist in both sets. It is the easiest way to find shared items between collections.
const odds = new Set([1, 3, 5, 7, 9]);
const squares = new Set([1, 4, 9]);
console.log(odds.difference(squares)); // Set(3) { 3, 5, 7 }
difference() removes values from the first set that are also present in the second. Use it when you want one set minus another.
const primes = new Set([2, 3, 5, 7, 11, 13, 17, 19]);
const squares = new Set([1, 4, 9, 16]);
console.log(primes.isDisjointFrom(squares)); // true
isDisjointFrom() tells you whether two sets share any common values. If they have no overlap, it returns true.
const fours = new Set([4, 8, 12, 16]);
const evens = new Set([2, 4, 6, 8, 10, 12, 14, 16, 18]);
console.log(fours.isSubsetOf(evens)); // true
isSubsetOf() checks whether all values in one set are contained by another set. This is great for validating permissions, feature flags, or allowed values.
const evens = new Set([2, 4, 6, 8, 10, 12, 14, 16, 18]);
const fours = new Set([4, 8, 12, 16]);
console.log(evens.isSupersetOf(fours)); // true
isSupersetOf() is the reverse of isSubsetOf(): it checks whether the first set contains every element of the second set.
const evens = new Set([2, 4, 6, 8]);
const squares = new Set([1, 4, 9]);
console.log(evens.symmetricDifference(squares)); // Set(5) { 2, 6, 8, 1, 9 }
symmetricDifference() returns values that appear in either set, but not both. It is useful when you want to filter out shared values and keep only unique items.
These new Set helpers make common set operations much easier to read and maintain. If you are working with collections in JavaScript, they are worth learning.