A Set holds unique values, compared with SameValueZero (the same rule as Map keys). Before ES2025 you wrote set algebra by hand with filter and spread. Set.prototype now has seven methods:
| Method | Result |
|---|---|
a.union(b) |
new Set of everything in a or b |
a.intersection(b) |
new Set of what is in both |
a.difference(b) |
new Set of a without b's members |
a.symmetricDifference(b) |
new Set of what is in exactly one of them |
a.isSubsetOf(b) |
true if every member of a is in b |
a.isSupersetOf(b) |
true if every member of b is in a |
a.isDisjointFrom(b) |
true if they share no member |
Properties worth stating in an interview:
- Non-mutating. The four algebra methods return a fresh, plain
Set(never a subclass instance);ais unchanged. - The argument is "set-like", not a
Set. The spec'sGetSetRecordreadssize,hasandkeysfrom it. AMapqualifies (its keys are used); an array does not, because it has nosize, so you get aTypeError. Wrap it:new Set(array). - Validation.
sizemust convert to a number that is notNaN(elseTypeError) and not negative (elseRangeError);hasandkeysmust be callable. - Ordering.
unionputsa's members first, thenb's new ones.intersectioniterates whichever side is smaller (compared bysize), so the result followsb's order whenbis smaller thana.
Support: Baseline since June 2024 per MDN, and available in Node 24 (run below).