Set composition methods
- Version
- es2025
- Since
- es2025
- Review
- Draft
Summary#
Set composition methods combine two collections into a new Set or answer a question about their membership. They leave both inputs unchanged.
Syntax#
const combined = first.union(second);
const contained = first.isSubsetOf(second);
The other set methods are intersection, difference, symmetricDifference, isSupersetOf and isDisjointFrom.
Example#
const granted = new Set(["read", "write"]);
const required = new Set(["write", "deploy"]);
console.log([...granted.union(required)].join(","));
console.log([...granted.intersection(required)].join(","));
console.log([...required.difference(granted)].join(","));
console.log([...granted.symmetricDifference(required)].join(","));
console.log(required.isSubsetOf(granted), granted.size);
console.log(granted.isSupersetOf(required), granted.isDisjointFrom(required));
Expected output#
read,write,deploy
write
deploy
read,deploy
false 2
false false
Common mistakes#
Call the methods on a Set. The argument can be set-like, with size, has and keys, so a Map works as a set of keys. Wrap arrays in new Set(array). Objects are compared by identity, even when their contents match.
Version applicability#
ES2025 added these methods. Older runtimes need a polyfill or explicit loops that call has.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0