Sub topic 2
New Sets In, Originals Untouched
Every set composition method added in ES2025 follows one rule. union, intersection, difference, and symmetricDifference each build a brand-new Set and return it. They never change the set you call them on, and they never change the set you pass in. The later chapters on each method build on this rule. This chapter covers what the rule promises, what it leaves out, and where it can catch you out.
This chapter assumes you can create a Set, use add, has, and delete, iterate with for...of, and tell an object reference apart from a primitive value. The examples run in any runtime that ships the ES2025 Set methods, such as Node.js 22 or later or a current browser.
What "returns a new Set" means
When you call a.union(b), the engine creates a fresh, empty Set object. It fills that object by reading elements from a and b, then hands it back to you. Neither a nor b is modified during the call.
You can check this with strict equality. The result is never the same object as either input, even when the contents happen to match.
const a = new Set([1, 2]);
const b = new Set([2, 3]);
const c = a.union(b);
console.log(c === a); // false
console.log(c === b); // false
// Even when nothing would change, you still get a new object
const same = a.union(new Set());
console.log(same === a); // false
console.log([...same]); // [1, 2]
const self = a.intersection(a);
console.log(self === a); // false
console.log([...a]); // [1, 2] (unchanged)
console.log([...b]); // [2, 3] (unchanged)So a.union(new Set()) works as a quick shallow copy, though new Set(a) says the same thing more clearly.
The methods at a glance
The seven new methods fall into two groups. Composition methods produce a set. Predicate methods produce a boolean and allocate no result set.
| Method | Returns | Changes the receiver? | Changes the argument? |
|---|---|---|---|
| `union` | new `Set` | No | No |
| `intersection` | new `Set` | No | No |
| `difference` | new `Set` | No | No |
| `symmetricDifference` | new `Set` | No | No |
| `isSubsetOf` | boolean | No | No |
| `isSupersetOf` | boolean | No | No |
| `isDisjointFrom` | boolean | No | No |
Compare these with the older Set methods. add, delete, and clear all mutate the set in place. If you are used to add returning the set itself for chaining, don't assume union behaves the same way. add returns the same set after changing it, while union returns a different set.
Results are independent of their inputs
The result set has no link back to the sets it came from. After the call returns, changes to the inputs do not show up in the result, and changes to the result do not show up in the inputs.
const owned = new Set(["read", "write"]);
const allowed = new Set(["read", "write", "delete"]);
const effective = owned.intersection(allowed);
owned.delete("write");
allowed.clear();
console.log([...effective]); // ["read", "write"]
effective.add("audit");
console.log(owned.has("audit")); // falseThe result is a snapshot of membership at the moment of the call. If you need a value that tracks its inputs as they change, recompute it, for example with a function that calls intersection each time you ask.
The copy is shallow
"Originals untouched" applies to set membership, meaning which values belong to which set. It does not apply to the values themselves. When an element is an object, the result holds the same reference as the input. The method does not clone it.
const user = { name: "Ana" };
const team = new Set([user]);
const reviewers = new Set([user]);
const both = team.intersection(reviewers);
const [member] = both;
console.log(member === user); // true
member.name = "Bea";
console.log(user.name); // "Bea"
console.log([...team][0].name); // "Bea"Changing member.name changed the one object that all three sets share. No set gained or lost an element, so the guarantee still holds. To isolate the objects as well, map over the result and clone each element, for example with structuredClone. Keep in mind that the clones are new references and will no longer match the originals in later set operations. The chapter on reference equality covers that matching rule in detail.
Subclasses are not preserved
If you subclass Set, the composition methods still return a plain Set. The specification creates the result directly from Set.prototype and does not consult Symbol.species or your constructor. It also fills the result through internal operations, so an overridden add on your subclass never runs for the result.
class TagSet extends Set {
add(value) {
// Normalize every tag to lowercase
return super.add(String(value).toLowerCase());
}
}
const tags = new TagSet(["JS", "Node"]);
console.log([...tags]); // ["js", "node"]
const merged = tags.union(new Set(["CSS"]));
console.log(merged instanceof TagSet); // false
console.log(merged instanceof Set); // true
console.log([...merged]); // ["js", "node", "CSS"]"CSS" stayed uppercase because the normalizing add was never called. If your subclass enforces an invariant like this one, wrap the result yourself, for example with new TagSet(tags.union(other)). The Set constructor calls this.add for every element, so your override runs on each element during construction.
Non-mutating is not the same as immutable
These methods don't mutate anything, but that doesn't make a Set immutable. Any code holding a reference can still call add, delete, or clear on any of them, including the results. Two common assumptions are wrong.
The first is that const protects the set. const only stops you from reassigning the variable to point at another object. The object itself can still change.
The second is that Object.freeze protects the set. Freezing only locks the object's own properties. A set's elements live in an internal slot that freezing does not reach.
const roles = Object.freeze(new Set(["viewer"]));
roles.add("admin"); // no error, even in strict mode
console.log(roles.has("admin")); // true
console.log(Object.isFrozen(roles)); // trueIf you need to protect a set that you hand to other code, give out a copy (new Set(internal)) instead of the original. The other option is to expose only read access through a function such as (value) => internal.has(value).
Why returning new sets helps
The non-mutating design has practical benefits.
- Safe sharing. You can pass a set into a helper that computes
input.difference(excluded)without worrying that the helper will empty your data. - Change detection by reference. UI libraries such as React decide whether state changed by comparing references.
setSelected(selected.union(newIds))produces a new reference, so the change is detected. Callingselected.add(id)and passing the same set back would not be detected. - Chaining. Each call returns a fresh
Set, so you can compose operations left to right:
const installed = new Set(["lodash", "react", "moment", "left-pad"]);
const required = new Set(["react", "zod"]);
const deprecated = new Set(["moment", "left-pad"]);
const keep = installed.difference(deprecated).union(required);
console.log([...keep]); // ["lodash", "react", "zod"]
console.log(installed.size); // 4 (unchanged)The cost: allocation
Every call allocates a new set and copies elements into it. For a single operation that cost is rarely noticeable. It does matter when you repeat the operation in a loop and reassign the result each time:
const batches = [
new Set([1, 2]),
new Set([2, 3]),
new Set([3, 4]),
];
// Copies the whole accumulated set on every iteration
let seenCopying = new Set();
for (const batch of batches) {
seenCopying = seenCopying.union(batch);
}
// Grows one set in place
const seenInPlace = new Set();
for (const batch of batches) {
for (const id of batch) seenInPlace.add(id);
}
console.log([...seenCopying]); // [1, 2, 3, 4]
console.log([...seenInPlace]); // [1, 2, 3, 4]With k batches and n total elements, the copying version can do up to roughly n × k element copies. The in-place version touches each element once. Chains also create intermediate sets. In a.difference(b).union(c), the set returned by difference exists only to be read by union, and then it becomes garbage.
When you own the set and nobody else holds a reference to it, mutating it in place is a reasonable choice. Here are the in-place equivalents:
const target = new Set([1, 2, 3, 4]);
const other = new Set([3, 4, 5]);
// In-place difference: remove everything in other
for (const x of other) target.delete(x);
console.log([...target]); // [1, 2]
// In-place intersection: keep only what is in other
const kept = new Set([1, 2, 3, 4]);
for (const x of kept) {
if (!other.has(x)) kept.delete(x);
}
console.log([...kept]); // [3, 4]Deleting the current element while iterating a Set with for...of is safe. The iterator skips removed entries and keeps going.
| Situation | Prefer |
|---|---|
| Inputs are shared, passed in, or part of app state | Non-mutating methods |
| You need to detect changes by reference | Non-mutating methods |
| One-off or small combination | Non-mutating methods |
| Building a large set across many iterations | In-place `add` / `delete` |
| Hot loop where allocation shows up in profiles | In-place `add` / `delete` |
Common mistakes
- Discarding the result. Writing
a.union(b);on its own line does nothing useful. The new set is created and thrown away, andais unchanged. Assign it:a = a.union(b)(withlet) orconst merged = a.union(b). - Expecting a subclass back.
instanceof MySetfails on results. Rewrap the result if you need the subclass. - Assuming elements are cloned. Object elements are shared, so mutation through one set is visible through every set that holds the same object.
- Relying on
Object.freezeorconst. Neither stopsadd,delete, orclear.
Exercise
After running const a = new Set([1, 2]); const b = new Set([2, 3]); a.union(b); a.add(9);, what does [...a] contain, and why?
Show answer
It contains [1, 2, 9]. The call a.union(b) built a new set that was immediately discarded because it was never assigned, so a never gained 3. Only the later a.add(9), which mutates in place, changed a.
Exercise
const item = { qty: 1 }; const s1 = new Set([item]); const s2 = s1.difference(new Set()); [...s2][0].qty = 5; What is item.qty, and does s1 === s2?
Show answer
item.qty is 5, and s1 === s2 is false. difference returned a new Set object, but the copy is shallow, so both sets hold the same object reference and the mutation is visible through item.
Exercise
You have class Upper extends Set { add(v) { return super.add(String(v).toUpperCase()); } } and const u = new Upper(["a"]);. What do u.union(new Set(["b"])) instanceof Upper and the spread of that result return, and how would you get an Upper containing "A" and "B"?
Show answer
instanceof Upper is false and the spread is ["A", "b"]. union returns a plain Set and fills it without calling the overridden add. Wrapping it as new Upper(u.union(new Set(["b"]))) runs add on every element and gives an Upper with ["A", "B"].
Exercise
A function receives an array of 10,000 small sets and must return their combined members. Should it use acc = acc.union(s) in a loop or a single accumulator with add? Justify your choice.
Show answer
Use a single accumulator set and add each element. The accumulator is local and not shared, so mutating it is safe. Repeated union would copy the growing accumulator on every one of the 10,000 iterations, which can mean far more copying than the one pass over each element that add needs.