Sub topic 6
Elements in Exactly One Set: symmetricDifference
This chapter assumes you already know how union, intersection, and difference work from the earlier chapters. You should also know that Set methods return a new Set and leave their inputs alone, and that elements are compared with SameValueZero.
symmetricDifference answers a specific question: which elements belong to one set or the other, but not to both? In set theory this is often written A △ B, and it works like a logical XOR applied element by element. If an element is in exactly one of the two sets, it is in the result. If it is in both or neither, it is left out.
The Basic Call
const a = new Set([1, 2, 3]);
const b = new Set([3, 4]);
const result = a.symmetricDifference(b);
console.log([...result]); // [1, 2, 4]
console.log([...a]); // [1, 2, 3] (unchanged)
console.log([...b]); // [3, 4] (unchanged)The value 3 is in both sets, so it is dropped. The values 1 and 2 are only in a, and 4 is only in b, so all three are kept. Like the other composition methods, symmetricDifference builds a fresh Set and leaves a and b unchanged.
The diagram below shows which region of two overlapping sets the method keeps.
Two Ways to Build It from Other Methods
You could compute the same result with the methods you already know. Writing out these equivalents helps you check your understanding of the method.
const a = new Set([1, 2, 3]);
const b = new Set([3, 4]);
// Everything, minus what is shared
const viaUnion = a.union(b).difference(a.intersection(b));
// What only a has, plus what only b has
const viaDifferences = a.difference(b).union(b.difference(a));
console.log([...viaUnion]); // [1, 2, 4]
console.log([...viaDifferences]); // [1, 2, 4]
console.log([...a.symmetricDifference(b)]); // [1, 2, 4]Both of these build intermediate Sets: two for the first form and three for the second. The native method makes a single pass over each input and allocates only the result, so use it whenever it is available. The equivalents are still useful for reasoning, and later in this chapter they also serve as a fallback.
How the Result Is Built
The specification gives a precise algorithm, and knowing it lets you predict both the contents and the order of the result.
- Copy every element of the receiver (
this) into a new result Set, in insertion order. - Iterate over the argument's keys, one at a time.
- For each key, check whether the receiver contains it.
- If the receiver has it, the element is shared, so remove it from the result.
- If the receiver does not have it, append it to the result if it is not already there.
- Return the result.
Some points follow directly from this algorithm:
- The method checks membership against the receiver, never the argument. It walks the argument only through its
keys()iterator. - It always iterates the whole argument.
intersectioncan choose to iterate the smaller set, butsymmetricDifferencehas no such shortcut, because every key of the argument might need to be appended. - If a custom
keys()iterator yields the same value twice, the "already in result" check prevents a duplicate.
Order: Same Contents, Different Sequence
Mathematically, A △ B equals B △ A. In JavaScript the contents are equal, but the iteration order depends on which set is the receiver.
const a = new Set([1, 2, 3]);
const b = new Set([3, 4]);
console.log([...a.symmetricDifference(b)]); // [1, 2, 4]
console.log([...b.symmetricDifference(a)]); // [4, 1, 2]The rule is that the receiver's surviving elements come first, in their original order, followed by the argument's unique elements in the order its keys() produced them. In b.symmetricDifference(a), the result starts as [3, 4]. Then 1 and 2 are appended and 3 is removed, which leaves [4, 1, 2].
If your code turns the result into an array for display, a stable sort, or a snapshot test, choose the receiver on purpose.
Applying It Twice Restores the Contents
XOR undoes itself: (a △ b) △ b has the same elements as a. This is the basis of the toggle pattern shown later. Element order, though, does not always come back.
const a = new Set([3, 1, 2]);
const b = new Set([4, 3]);
const once = a.symmetricDifference(b);
console.log([...once]); // [1, 2, 4]
const twice = once.symmetricDifference(b);
console.log([...twice]); // [1, 2, 3]
console.log([...a]); // [3, 1, 2]
console.log(twice.size === a.size && twice.isSubsetOf(a)); // trueWalking b on the second call removes 4, because once has it, and appends 3 at the end, because once does not. The element 3 moves from first place to last. The contents match a, but the order does not.
Edge Cases
Identical, disjoint, and empty sets
| Situation | Result | Why |
|---|---|---|
| `a` and `b` have the same elements | Empty Set | Every element is shared |
| `a` and `b` share nothing | Same contents as `a.union(b)` | Nothing is removed |
| `b` is empty | Same contents and order as `a` | No keys to process |
| `a` is empty | Same contents and order as `b` | Every key is appended |
| `a.symmetricDifference(a)` | Empty Set | Every key is found in the receiver |
const a = new Set(["x", "y"]);
console.log(a.symmetricDifference(a).size); // 0
console.log([...a.symmetricDifference(new Set())]); // ["x", "y"]
console.log([...new Set().symmetricDifference(a)]); // ["x", "y"]
console.log(a.symmetricDifference(new Set(["z"])).size); // 3NaN, zero, and SameValueZero
Membership uses SameValueZero, so NaN matches NaN, and 0 matches -0. Keys that come from the argument are also normalized, so -0 becomes +0.
const left = new Set([NaN, 0]);
const right = new Set([NaN, -0]);
console.log(left.symmetricDifference(right).size); // 0Objects compare by reference
Two objects with the same contents are still different elements. The chapter on reference equality covers this in detail. For symmetricDifference, it means look-alike objects survive from both sides:
const shared = { id: 1 };
const a = new Set([shared, { id: 2 }]);
const b = new Set([shared, { id: 2 }]);
console.log(a.symmetricDifference(b).size); // 2 (both separate { id: 2 } objects)If you need to compare by value, map the objects to a primitive key such as id first, run the set operation on the keys, and then look the objects up again.
Arguments: Maps, Custom Objects, and Arrays
Like the other methods, symmetricDifference accepts any set-like argument: an object with a numeric size and callable has and keys methods. A Map qualifies, and its keys are used:
const tags = new Set(["a", "b"]);
const counts = new Map([["b", 1], ["c", 2]]);
console.log([...tags.symmetricDifference(counts)]); // ["a", "c"]The algorithm never calls the argument's has, but has must still exist, because every Set method checks the full protocol before it starts. Here is a custom set-like object that logs its calls:
const evens = {
size: 3,
has(x) {
console.log("has called");
return x === 2 || x === 4 || x === 6;
},
*keys() {
yield 2;
yield 4;
yield 6;
},
};
console.log([...new Set([1, 2, 3]).symmetricDifference(evens)]); // [1, 3, 4, 6]
// "has called" is never printed
const broken = { size: 1, *keys() { yield 1; } };
try {
new Set([1]).symmetricDifference(broken);
} catch (err) {
console.log(err instanceof TypeError); // true (has is missing)
}An array has no size property, so passing one throws a TypeError. Wrap it first:
const current = new Set(["a", "b"]);
const incoming = ["b", "c"];
try {
current.symmetricDifference(incoming);
} catch (err) {
console.log(err instanceof TypeError); // true
}
console.log([...current.symmetricDifference(new Set(incoming))]); // ["a", "c"]A Fallback for Older Runtimes
The support chapter covers feature detection in general. The following fallback matches the native method's contents and order: the receiver's unique elements first, then the argument's unique elements.
function symmetricDifference(a, b) {
if (typeof a.symmetricDifference === "function") {
return a.symmetricDifference(b);
}
return new Set([
...[...a].filter((x) => !b.has(x)),
...[...b].filter((x) => !a.has(x)),
]);
}
console.log([...symmetricDifference(new Set([1, 2, 3]), new Set([3, 4]))]); // [1, 2, 4]The two paths behave differently in some cases. When b is a Map, the fallback spreads [key, value] entries instead of keys. When b is an array, the fallback throws because b.has does not exist. That error happens to match the native behavior, but it happens for a different reason. If the fallback has to accept Maps, iterate b.keys() instead of spreading b.
Practical Uses
Toggling a batch of selections
Clicking a group of items in a multi-select UI should select the ones that are off and deselect the ones that are on. That is exactly XOR:
let selected = new Set(["a", "b", "c"]);
const clicked = new Set(["b", "d"]);
selected = selected.symmetricDifference(clicked);
console.log([...selected]); // ["a", "c", "d"]Because selected stays the receiver, items that stay selected keep their order, and newly selected items go at the end.
Detecting drift between two lists
To check whether two ID lists or configuration key sets agree, take the symmetric difference and test its size. An empty result means the two match. A non-empty result lists every mismatch at once. Use difference in each direction when you need to know which side each mismatch came from.
const expectedKeys = new Set(["host", "port", "timeout"]);
const actualKeys = new Set(Object.keys({ host: "x", port: 80, retries: 3 }));
const drift = expectedKeys.symmetricDifference(actualKeys);
console.log(drift.size === 0); // false
console.log([...drift]); // ["timeout", "retries"]
console.log([...expectedKeys.difference(actualKeys)]); // ["timeout"] (missing)
console.log([...actualKeys.difference(expectedKeys)]); // ["retries"] (unexpected)Exercise
Given const p = new Set(["x", "y", "z"]) and const q = new Set(["z", "w", "x"]), what do [...p.symmetricDifference(q)] and [...q.symmetricDifference(p)] print?
Show answer
p.symmetricDifference(q) starts as ["x", "y", "z"]. Walking q removes "z", appends "w", and removes "x", which gives ["y", "w"]. q.symmetricDifference(p) starts as ["z", "w", "x"]. Walking p removes "x", appends "y", and removes "z", which gives ["w", "y"]. The contents are the same and the order differs.
Exercise
What does new Set([1, 2]).symmetricDifference(new Map([[2, "a"], [3, "b"]])) return, and what would the spread-and-filter fallback from this chapter return for the same inputs?
Show answer
The native method uses the Map's keys and returns a Set containing 1 and 3. The fallback spreads the Map into [2, "a"] and [3, "b"] entry arrays. Neither array is a key of the Set, so the result is {1, 2, [2, "a"], [3, "b"]}, which is wrong. The fallback should iterate b.keys() to handle Maps.
Exercise
Write an expression that is true exactly when Sets a and b contain the same elements, using symmetricDifference.
Show answer
a.symmetricDifference(b).size === 0. The symmetric difference is empty only when no element belongs to just one of the two sets, which means the sets have the same contents, whatever their order.