Sub topic 9
What Order Do Results Come In?
A Set remembers the order its elements were inserted, and iterating it with for...of or spread always follows that order. When union, intersection, difference, or symmetricDifference builds a new Set, the new Set has an order too. Most of the time that order is easy to predict. One method has a gotcha that catches people who write tests or UI code that depends on order.
This chapter assumes you already know how each of the four composition methods works (covered in earlier chapters), and that you are comfortable with spread syntax and Array.prototype.filter. To run the examples you need a runtime with the ES2025 Set methods, such as Node.js 22 or later, or a current version of Chrome, Firefox, or Safari.
The Rule Underneath Everything
A Set's iteration order is its insertion order. Two details decide where elements end up:
- Calling
addwith a value that is already present does nothing. The value keeps its original position. - Deleting a value and adding it again moves it to the end.
const s = new Set(["a", "b", "c"]);
s.add("a"); // already present: no change
console.log([...s]); // ["a", "b", "c"]
s.delete("a");
s.add("a"); // removed, then re-added at the end
console.log([...s]); // ["b", "c", "a"]The composition methods follow the same rule. Each one either starts from a copy of the receiver (the set you call the method on) and adds or removes elements, or starts empty and appends elements as it finds them. To predict the output order, you only need to know which set the algorithm walks through and which one it just looks things up in.
union: Receiver First, Then the Newcomers
union copies the receiver, then walks the argument's keys() and appends each element that isn't already in the result.
const a = new Set(["red", "green", "blue"]);
const b = new Set(["yellow", "blue", "purple", "red"]);
console.log([...a.union(b)]);
// ["red", "green", "blue", "yellow", "purple"]
console.log([...b.union(a)]);
// ["yellow", "blue", "purple", "red", "green"]Shared elements such as "blue" and "red" stay where the receiver had them. Their position in the argument doesn't matter, because appending a value that is already present has no effect. The argument's new elements arrive in the argument's own order.
So a.union(b) and b.union(a) contain the same elements in different orders. As mathematical sets they are equal. As arrays they are not.
difference: Always the Receiver's Order
difference starts from a copy of the receiver and only removes elements from it. Removing an element never reorders the ones that remain, so the result is always a subsequence of the receiver.
const all = new Set([5, 1, 4, 2, 3]);
const remove = new Set([3, 9, 5]);
console.log([...all.difference(remove)]); // [1, 4, 2]Internally, the method picks one of two strategies depending on which set is smaller. When the receiver is smaller or the same size, it walks the receiver and calls the argument's has. When the receiver is larger, it walks the argument's keys() and deletes matches from the copy. Both strategies remove the same elements from the same copy, so the order of the result is identical either way.
symmetricDifference: Receiver's Leftovers, Then the Argument's
symmetricDifference also starts from a copy of the receiver. It then walks the argument's keys(). For each element, it removes the element from the result if the original receiver had it, and appends it if not.
const a = new Set([1, 2, 3, 4]);
const b = new Set([6, 4, 5, 2]);
console.log([...a.symmetricDifference(b)]); // [1, 3, 6, 5]
console.log([...b.symmetricDifference(a)]); // [6, 5, 1, 3]The result is the receiver's unshared elements in receiver order, followed by the argument's unshared elements in argument order. This method has no size-based branching, so it always behaves this way.
intersection: The Order Depends on Size
intersection is the method that surprises people. Like difference, it picks a strategy by comparing sizes. Unlike difference, it builds its result from an empty Set by appending matches, so the set it walks decides the order:
- Receiver size ≤ argument size: walk the receiver, call
other.has(e)for each element, and append matches. The result is in receiver order. - Receiver size > argument size: walk
other.keys(), check each value against the receiver's internal data, and append matches. The result is in argument order.
Here is the effect with the same receiver and two different arguments:
const a = new Set(["x", "y", "z"]);
const small = new Set(["z", "x"]); // size 2 < 3
const big = new Set(["z", "x", "q", "r"]); // size 4 >= 3
console.log([...a.intersection(small)]); // ["z", "x"] (argument order)
console.log([...a.intersection(big)]); // ["x", "z"] (receiver order)Both results hold exactly "x" and "z", but the order flips. The only change is whether the argument is smaller than the receiver. This is why the specification doesn't promise that intersection preserves the receiver's order.
The size strategy is there for performance. Walking the smaller set means fewer lookups, so the cost depends on the smaller set's size rather than the larger one's. The order behavior is a side effect of that choice.
Watching the Strategy Happen
You can see which path runs by passing a Set subclass that logs calls to has and keys. A later chapter covers set-like arguments in detail. For now, all you need to know is that the methods call the argument's has and keys methods instead of reading its internal data.
class LoggingSet extends Set {
has(value) {
console.log(` has(${JSON.stringify(value)})`);
return super.has(value);
}
keys() {
console.log(" keys()");
return super.keys();
}
}
const receiver = new Set(["x", "y", "z"]);
console.log("Argument larger:");
const r1 = receiver.intersection(new LoggingSet(["z", "x", "q", "r"]));
console.log(" ", [...r1]);
console.log("Argument smaller:");
const r2 = receiver.intersection(new LoggingSet(["z", "x"]));
console.log(" ", [...r2]);Output:
Argument larger:
has("x")
has("y")
has("z")
[ 'x', 'z' ]
Argument smaller:
keys()
[ 'z', 'x' ]In the first call, the receiver is walked and the argument is only queried. In the second, the argument is walked through keys() and its has is never called.
Summary Table
| Method | How the result is built | Result order |
|---|---|---|
| `a.union(b)` | Copy `a`, append new elements from `b.keys()` | `a`'s order, then `b`'s new elements in `b`'s order |
| `a.intersection(b)` | Start empty, walk the smaller set | `a`'s order if `a.size <= b.size`, otherwise `b`'s order |
| `a.difference(b)` | Copy `a`, remove matches | `a`'s order, always |
| `a.symmetricDifference(b)` | Copy `a`, walk `b.keys()`, remove shared and append new | `a`'s remaining elements, then `b`'s unshared elements in `b`'s order |
The predicates isSubsetOf, isSupersetOf, and isDisjointFrom return booleans, so order never affects them. Order does affect how quickly they return, since they can stop at the first counterexample. It never affects the answer.
Order and Fallback Code
Fallbacks for older runtimes are usually written with spread and filter. Check that each one produces the same order as the native method:
const a = new Set([1, 2, 3, 4]);
const b = new Set([4, 2]);
// union: matches native order exactly
const u = new Set([...a, ...b]);
// difference: matches native order exactly
const d = new Set([...a].filter((x) => !b.has(x)));
// symmetricDifference: matches native order exactly
const sd = new Set([
...[...a].filter((x) => !b.has(x)),
...[...b].filter((x) => !a.has(x)),
]);
// intersection: ALWAYS a's order, unlike native when a is larger
const i = new Set([...a].filter((x) => b.has(x)));
console.log([...u]); // [1, 2, 3, 4]
console.log([...d]); // [1, 3]
console.log([...sd]); // [1, 3]
console.log([...i]); // [2, 4]
if (typeof a.intersection === "function") {
console.log([...a.intersection(b)]); // [4, 2] (b's order, since a is larger)
}The filter-based intersection fallback is more predictable than the native method, because it always keeps the receiver's order. Code that runs native in one environment and the fallback in another can therefore return the same intersection in different orders. If order reaches the user, for example as a rendered tag list, normalize it explicitly instead of trusting either implementation.
Testing Without Order Surprises
If a test turns Set results into arrays and compares them, the comparison becomes order-sensitive. A test like that can pass for union and then break for intersection when someone changes the input sizes. Compare Sets as sets:
function sameElements(x, y) {
return x.size === y.size && x.isSubsetOf(y);
}
const a = new Set(["x", "y", "z"]);
const small = new Set(["z", "x"]);
console.log(sameElements(a.intersection(small), new Set(["x", "z"]))); // trueNode's assert.deepStrictEqual also compares Set contents without regard to order, so you can pass Sets to it directly. When order really is part of the requirement, sort before comparing: [...result].sort() for strings, or .sort((p, q) => p - q) for numbers.
Edge Cases Worth Knowing
- Equal sizes: the receiver-walking path runs when
a.size <= b.size, so an intersection of two equal-sized sets follows the receiver's order. - Empty sets: an empty receiver or argument produces an empty result, so order doesn't apply.
- Duplicate keys from custom set-likes: a hand-written set-like object could yield the same value twice from
keys().unionandintersectionskip values already in the result, so duplicates never show up and never change position. - Earlier deletes and re-adds: results follow each input's current insertion order. A value that was deleted and re-added earlier counts as one of the newest elements in that set.
Exercise
Given const a = new Set([10, 20, 30, 40]) and const b = new Set([40, 10]), what do [...a.intersection(b)] and [...b.intersection(a)] print, and why?
Show answer
Both print [40, 10]. For a.intersection(b), a.size (4) is greater than b.size (2), so the method walks b.keys() and the result follows b's order. For b.intersection(a), b.size (2) is less than or equal to a.size (4), so it walks the receiver b, again in b's order. Both calls walk the smaller set.
Exercise
What does [...new Set(["c", "a"]).union(new Set(["b", "a", "d"]))] print, and what does the symmetricDifference of the same two sets print?
Show answer
The union prints ["c", "a", "b", "d"]: the receiver's elements first, then "b" and "d" from the argument in its order, with "a" left at the receiver's position. The symmetricDifference prints ["c", "b", "d"]: "a" is removed because both sets have it, the receiver's leftover "c" comes first, and the argument's unshared "b" and "d" follow in argument order.
Exercise
A component renders a.intersection(b) as a list of tags. It shows the tags in a's order in development but in a different order in production. Name a likely cause and a fix.
Show answer
The relative sizes of a and b probably differ between the two environments. When a is larger than b, the native intersection follows b's order. Another possible cause is that one environment uses a filter-based fallback, which always keeps a's order, while the other uses the native method. The fix is to normalize the order explicitly, for example new Set([...a].filter((t) => b.has(t))) to force a's order, or to sort the tags before rendering.