New Set methods let developers perform common set operations directly on Set objects without extra code.
union()
The union() method creates a new Set containing every element that appears in either of the source sets. It eliminates duplicates automatically, so you get a clean combined collection.
- Accepts another
Setas an argument. - Returns a brand‑new
Set-the original sets stay unchanged. - Works with strings, numbers, objects, or any value that a
Setcan hold. - Runs in constant time per element, making it fast for large collections.
- Useful for merging user‑generated lists, tag collections, or API results.
intersection()
intersection() builds a Set of values that exist in both source sets. This is handy when you need to find common items across datasets.
- Requires a second
Setto compare against. - Produces a new
Setcontaining only shared elements. - Preserves the original sets for further reuse.
- Ideal for filtering overlapping tags, permissions, or feature flags.
- Complex objects are compared by reference, matching JavaScripts native behavior.
difference()
The difference() method returns a Set with elements that are present in the first set but not in the second. Think of it as set A minus set B.
- Accepts a single
Setargument. - Outputs a new
Setcontaining the exclusive items of the first set. - Helpful for removing processed IDs or filtering out revoked permissions.
- Operates without mutating the original collections.
- Works consistently across Firefox 127, Chrome 120, Edge 120, and Safari 17.
symmetricDifference()
symmetricDifference() produces a Set of items that appear in either set but not in both. Its the complement of intersection().
- Takes another
Setas input. - Returns a new
Setwith elements exclusive to each source set. - Great for highlighting changes between two versions of data.
- Maintains original sets unchanged, enabling chainable operations.
- Can be combined with
union()andintersection()for custom logic.
isSubsetOf() and isSupersetOf()
These predicate methods let you test hierarchical relationships between sets. isSubsetOf() returns true if every element of the first set exists in the second, while isSupersetOf() does the opposite.
- Both accept a single
Setargument. - Return a boolean value for quick conditional checks.
- Useful for permission checks, feature toggles, or validating data scopes.
- Do not create new objects, keeping memory usage low.
- Example usage is shown in the MDN documentation for Set.
For a deeper dive into set theory concepts, see the Wikipedia article. If youre interested in how set‑like operations map to real‑world workflows, check out our guide on triangular workflows in Git and the real‑time payment orchestration framework for architectural parallels.