Sub topic 3
Combining Sets with union
Set.prototype.union takes two sets and returns a new Set holding every element found in either one. Before ES2025 you wrote this yourself with spread syntax. Now it is a single method call with defined ordering and defined error behavior.
This chapter assumes you can create and iterate a Set, that you know spread syntax and arrow functions, and that you know the difference between object references and primitive values. The earlier chapters covered two points this one relies on: Set compares elements with SameValueZero, and the composition methods always return a new Set without changing their inputs.
The basic call
The method is called on one set, the receiver, and takes another set-like value, the argument. It returns a fresh Set.
const frontend = new Set(["js", "css", "html"]);
const backend = new Set(["js", "sql"]);
const all = frontend.union(backend);
console.log([...all]); // ["js", "css", "html", "sql"]
console.log(all.size); // 4
console.log(frontend.size); // 3 (unchanged)
console.log(backend.size); // 2 (unchanged)
console.log(all === frontend); // falseThe string "js" appears in both inputs but only once in the result. That follows from Set uniqueness: an element already present is not added again.
In set notation, A.union(B) is A ∪ B. Union is commutative, so a.union(b) and b.union(a) always contain the same elements and have the same size. The iteration order is a separate question, covered next.
How union builds its result
The specification describes union as a short algorithm. Knowing it lets you predict both the ordering and the errors.
The algorithm has three points worth noting:
- Validation happens first. The argument's
size,has, andkeysproperties are read and checked before any elements are copied. Ifsizeconverts toNaN, or ifhasorkeysis not a function, aTypeErroris thrown. A negativesizethrows aRangeError. - Only
keysis used for the merge. Union has to visit every element of the argument, so it iterateskeys(). It never callshason the argument, buthasmust still exist because validation checks for it. - The receiver goes first. The result starts as a copy of the receiver. The argument's elements are appended afterward, and only if they are new.
Order of the result
Because of that algorithm, the order is fully defined:
- All of the receiver's elements come first, in the receiver's insertion order.
- Then come the argument's elements that the receiver did not already contain, in the order the argument's
keys()produces them.
const a = new Set(["c", "a"]);
const b = new Set(["b", "a", "d"]);
console.log([...a.union(b)]); // ["c", "a", "b", "d"]
console.log([...b.union(a)]); // ["b", "a", "d", "c"]Both results have size 4 and hold the same elements, but they iterate differently. A shared element such as "a" keeps the position it has in the receiver. Its position in the argument has no effect.
This matters when the order of a Set carries meaning, for example when you render a list of tags or build a priority list. Put the set whose order you want to keep on the left.
Equality rules: SameValueZero in practice
Union decides "already present" with the same SameValueZero comparison that Set.prototype.has uses. In practice this means:
| Values compared | Considered equal? | Effect in union |
|---|---|---|
| `1` and `1` | Yes | One element |
| `"1"` and `1` | No | Two elements |
| `NaN` and `NaN` | Yes | One element |
| `0` and `-0` | Yes | One element, stored as `+0` |
| Two different objects with the same contents | No | Two elements |
| The same object reference twice | Yes | One element |
const nums = new Set([1, NaN, 0]);
const more = new Set(["1", NaN, -0]);
const merged = nums.union(more);
console.log(merged.size); // 4
console.log([...merged]); // [1, NaN, 0, "1"]
console.log(Object.is([...merged][2], -0)); // false (it is +0)Object identity gets its own chapter later. The short version for union is that new Set([{ id: 1 }]).union(new Set([{ id: 1 }])) has size 2, because the two object literals are different references.
union with Map and other set-like arguments
The argument does not have to be a Set. It only needs to be set-like: a numeric size, a callable has, and a callable keys that returns an iterator. A Map qualifies, and union takes its keys.
const ids = new Set([1, 2]);
const scores = new Map([[2, "B"], [3, "A"]]);
console.log([...ids.union(scores)]); // [1, 2, 3]The map's values ("B", "A") are ignored, and only keys are merged.
A plain custom object works as long as it follows the protocol:
const smallRange = {
size: 3,
has(x) {
return x >= 1 && x <= 3;
},
keys() {
return [1, 2, 3][Symbol.iterator]();
},
};
console.log([...new Set([0, 2]).union(smallRange)]); // [0, 2, 1, 3]Arrays are the most common mistake. An array has no size property, so size reads as undefined, converts to NaN, and validation throws:
const tags = new Set(["a", "b"]);
try {
tags.union(["c"]);
} catch (err) {
console.log(err instanceof TypeError); // true
}
console.log([...tags.union(new Set(["c"]))]); // ["a", "b", "c"]Wrap arrays with new Set(array) first. The Set constructor accepts any iterable, so it is the right adapter here. The set-like protocol chapter covers the other requirements in detail.
Common mistakes
Expecting the receiver to change
Union is not an in-place operation. This code silently does nothing useful:
const permissions = new Set(["read"]);
permissions.union(new Set(["write"])); // result discarded
console.log(permissions.has("write")); // falseAssign the result: const updated = permissions.union(extra);. If you really want to mutate the original Set, for example because other code holds a reference to it, add elements in a loop:
const permissions = new Set(["read"]);
for (const p of new Set(["write", "read"])) {
permissions.add(p);
}
console.log([...permissions]); // ["read", "write"]Expecting a subclass back
The result is always a plain Set, even when the receiver is a subclass. The methods intentionally do not use Symbol.species or the receiver's constructor.
class TagSet extends Set {
describe() {
return [...this].join(", ");
}
}
const t = new TagSet(["x"]);
const u = t.union(new Set(["y"]));
console.log(u instanceof TagSet); // false
console.log(u instanceof Set); // true
console.log(typeof u.describe); // "undefined"If you need the subclass, wrap the result: new TagSet(t.union(other)).
Passing more than one argument
union takes exactly one argument. Any extra arguments are ignored, with no error:
const a = new Set([1]);
const b = new Set([2]);
const c = new Set([3]);
console.log([...a.union(b, c)]); // [1, 2] (c ignored)Combining many sets
To merge more than two sets, chain the calls or use reduce:
const a = new Set([1, 2]);
const b = new Set([2, 3]);
const c = new Set([3, 4]);
console.log([...a.union(b).union(c)]); // [1, 2, 3, 4]
const posts = [
{ title: "Intro", tags: ["js", "web"] },
{ title: "Styling", tags: ["css", "web"] },
{ title: "Servers", tags: ["js", "node"] },
];
const allTags = posts
.map((post) => new Set(post.tags))
.reduce((acc, set) => acc.union(set), new Set());
console.log([...allTags]); // ["js", "web", "css", "node"]The ordering rule still applies at each step, so the result lists tags in first-seen order across the posts.
Every call copies the accumulated result into a new Set. With many large sets, repeated reduce calls copy the growing result again and again. When performance matters more than immutability, build one Set and add to it:
function unionAll(sets) {
const result = new Set();
for (const set of sets) {
for (const value of set) {
result.add(value);
}
}
return result;
}
console.log([...unionAll([new Set([1]), new Set([1, 2]), new Set([3])])]); // [1, 2, 3]This gives the same elements in the same order without the intermediate copies. Because result is created inside the function, the caller's sets stay unchanged.
union compared with the spread idiom
Before ES2025 the usual way to write a union was new Set([...a, ...b]). For two real Sets it produces the same elements in the same order, because spreading keeps insertion order and the constructor skips duplicates.
| Aspect | `a.union(b)` | `new Set([...a, ...b])` |
|---|---|---|
| Result order | Receiver first, then new argument elements | Same |
| Accepts a Map | Yes, uses its keys | Spreads `[key, value]` pairs, so you get arrays as elements |
| Accepts an array | Throws `TypeError` | Works |
| Intermediate array | None | Builds a temporary array |
| Runtime support | ES2025 runtimes only | Any ES2015 runtime |
The Map row is a real gotcha. new Set([...ids, ...scores]) does not merge keys. It adds entries like [2, "B"] as array elements. union does what you would expect. The fallback chapter shows how to feature-detect union and fall back to the spread form safely.
Exercise
Given const a = new Set(["x", "y"]); and const b = new Set(["z", "y", "w"]);, what do [...a.union(b)] and [...b.union(a)] print, and why do they differ?
Show answer
[...a.union(b)] prints ["x", "y", "z", "w"] and [...b.union(a)] prints ["z", "y", "w", "x"]. The result starts with the receiver's elements in insertion order, then appends the argument's elements that are not already present, in the argument's order. The shared element "y" keeps the receiver's position. Both results have size 4.
Exercise
A colleague writes const ids = new Set([1, 2]); const merged = ids.union([2, 3]);. What happens, and what is the smallest fix?
Show answer
It throws a TypeError. An array has no size property, so validation reads undefined, converts it to NaN, and rejects the argument. Wrap the array: ids.union(new Set([2, 3])), which gives [1, 2, 3].
Exercise
What is the size of new Set([0, NaN, { k: 1 }]).union(new Set([-0, NaN, { k: 1 }])), and why?
Show answer
The size is 4. Under SameValueZero, -0 equals 0 and NaN equals NaN, so neither is added a second time. The two { k: 1 } literals are different object references, so both are kept. The elements are 0, NaN, the first object, and the second object.
Exercise
Write a function mergeKeys(map1, map2) that returns a Set of every key from two Maps, with map1's keys first, using union.
Show answer
const mergeKeys = (map1, map2) => new Set(map1.keys()).union(map2);. new Set(map1.keys()) builds a Set from the first map's keys in insertion order. union accepts the second Map as a set-like argument and appends its keys that are not already present.