Sub topic 5
Removing Elements with difference
This chapter assumes you can create and iterate a Set, use spread syntax and Array.prototype.filter, and know that set methods return a new Set instead of changing the original. You should also have worked through union and intersection, because difference is easiest to understand next to them.
Set.prototype.difference answers one question: which elements of this set are not in that other set? It is the only basic composition method where the order of the two sets changes the answer, and most bugs with it come from that.
What difference Returns
a.difference(b) returns a new Set containing every element of a that b does not have. Elements that appear only in b are ignored. Neither a nor b changes.
const subscribed = new Set(["alice", "bob", "carol", "dave"]);
const unsubscribed = new Set(["bob", "dave", "erin"]);
const stillSubscribed = subscribed.difference(unsubscribed);
console.log([...stillSubscribed]); // ["alice", "carol"]
console.log(subscribed.size); // 4 (unchanged)
console.log(unsubscribed.size); // 3 (unchanged)"erin" appears in unsubscribed but not in subscribed, so it has nothing to remove and does not affect the result. You can think of difference as subtraction: start with a copy of the receiver and take away anything the argument also contains.
The receiver sets the scope
The set you call the method on is the receiver. The result can only ever contain elements from the receiver, so the result is always a subset of it.
Direction Matters
union and intersection give the same elements whichever way round you call them. They differ at most in order. difference does not work that way. a.difference(b) and b.difference(a) usually hold completely different elements.
const a = new Set([1, 2, 3, 4]);
const b = new Set([3, 4, 5]);
console.log([...a.difference(b)]); // [1, 2]
console.log([...b.difference(a)]); // [5]To keep the direction straight, read the call aloud as "a without b". The receiver is what you have. The argument is what you take away.
A real task often needs both directions. Synchronising a local list of IDs with a server list is a common case:
const localIds = new Set([101, 102, 103, 104]);
const serverIds = new Set([103, 104, 105, 106]);
const toCreate = serverIds.difference(localIds); // on server, missing locally
const toDelete = localIds.difference(serverIds); // local, gone from server
console.log([...toCreate]); // [105, 106]
console.log([...toDelete]); // [101, 102]If you swapped the two calls, the code would delete records the server has just added. When a difference result looks wrong, check the direction first.
How Elements Are Compared
Membership is decided with SameValueZero, the same rule Set uses everywhere. In practice:
- Primitives with the same value match:
"a"matches"a",3matches3. NaNmatchesNaN, unlike with===.0and-0match each other.- Objects match only if they are the same reference.
const values = new Set([NaN, 0, 1, "1"]);
const remove = new Set([NaN, -0, 1]);
console.log([...values.difference(remove)]); // ["1"]NaN and 0 are removed because SameValueZero treats them as equal to NaN and -0. The string "1" survives because it is a different type from the number 1. No type coercion happens.
Object identity is covered in its own chapter, but it catches people with difference in a particular way. Removing objects whose contents look equal removes nothing:
const users = new Set([{ id: 1 }, { id: 2 }]);
const banned = new Set([{ id: 1 }]);
console.log(users.difference(banned).size); // 2 (nothing removed)If your elements are objects, subtract on a key such as an ID, or make sure both sets hold the same object references.
Ordering of the Result
The result keeps the receiver's insertion order. That stays true however the engine decides to do the work. You can see it with sets of very different sizes:
const a = new Set([5, 3, 1, 4]);
const bigger = new Set([1, 9, 8, 7, 6, 2]);
console.log([...a.difference(bigger)]); // [5, 3, 4]
const big = new Set([10, 20, 30, 40, 50]);
const small = new Set([40, 10]);
console.log([...big.difference(small)]); // [20, 30, 50]In both calls the surviving elements come out in the order they were added to the receiver. The argument's order never matters, because no element of the argument ends up in the result.
How It Works Internally
The specification defines difference as "copy the receiver, then remove matches". It picks between two strategies depending on which set is smaller:
- Start the result as a copy of the receiver's elements.
- If the receiver's size is less than or equal to the argument's
size, loop over the receiver and call the argument'shasfor each element. Remove every element for whichhasreturnstrue. - Otherwise, loop over the argument's
keys()iterator and remove each yielded value from the result if it is there.
Both strategies cost time in proportion to the smaller set, which helps when one set is huge and the other tiny. Because the work starts from a copy of the receiver and only deletes from it, the receiver's order is preserved either way.
You can watch the choice happen by passing a set-like object that logs its calls. A set-like object is anything with a numeric size and callable has and keys methods. The set-like protocol has its own chapter.
function logging(set) {
return {
size: set.size,
has(v) {
console.log("has", v);
return set.has(v);
},
keys() {
console.log("keys");
return set.keys();
},
};
}
// Receiver (2) is not bigger than argument (3): uses has
console.log([...new Set([1, 2]).difference(logging(new Set([2, 3, 4])))]);
// has 1
// has 2
// [1]
// Receiver (4) is bigger than argument (1): uses keys
console.log([...new Set([1, 2, 3, 4]).difference(logging(new Set([2])))]);
// keys
// [1, 3, 4]This matters for custom set-like objects. If your has and keys disagree, for example because has is case-insensitive and keys yields the original casing, the result can change with the relative sizes of the two sets. Keep the two methods consistent.
Edge Cases
| Expression | Result | Why |
|---|---|---|
| `a.difference(a)` | empty Set | Every element is in the argument |
| `a.difference(new Set())` | copy of `a` | Nothing to remove |
| `new Set().difference(b)` | empty Set | Nothing to start with |
| `a.difference(b).size === 0` | `true` exactly when `a.isSubsetOf(b)` | No element of `a` is outside `b` |
| `a.difference([1, 2])` | throws `TypeError` | Arrays have no `size` property |
| `a.difference(new Map([[1, "x"]]))` | `a` without key `1` | Maps are set-like through their keys |
A few more details are worth knowing:
- The result is always a fresh object, even when nothing is removed.
a.difference(new Set()) === aisfalse. - The result is a plain
Set. If you subclassSet, the result is not an instance of your subclass. The new methods do not useSymbol.species.
class TagSet extends Set {}
const tags = new TagSet(["a", "b"]);
const result = tags.difference(new Set(["a"]));
console.log(result instanceof TagSet); // false
console.log(result instanceof Set); // trueChaining and Removing Several Sets
Since difference returns a Set, you can chain calls to subtract several sets in turn. The order of the later arguments does not change the elements in the result, because each step only removes.
const allFeatures = new Set(["search", "export", "share", "beta-ai", "admin"]);
const disabledByPlan = new Set(["admin"]);
const disabledByRegion = new Set(["beta-ai"]);
const available = allFeatures
.difference(disabledByPlan)
.difference(disabledByRegion);
console.log([...available]); // ["search", "export", "share"]Each link in the chain builds a new intermediate Set. For a handful of sets that cost does not matter. If you are subtracting dozens of sets in a hot loop, you can union the removals first with disabledByPlan.union(disabledByRegion) and subtract once, or delete from a single copy with forEach.
difference Versus a filter Fallback
Before ES2025 the usual way to write this was:
const a = new Set([1, 2, 3, 4]);
const b = new Set([3, 4, 5]);
const legacy = new Set([...a].filter((x) => !b.has(x)));
console.log([...legacy]); // [1, 2]This gives the same elements in the same order. It has three differences from the native method:
- It always iterates the receiver, so it cannot take the cheaper path when the argument is much smaller.
- It builds an intermediate array.
- It accepts any
bwith ahasmethod, so it will not throw for inputs the native method rejects. A bug that would surface as aTypeErrorwith the native method can go unnoticed here.
Feature detection and wrapping the fallback in a helper are covered in the browser support chapter.
Common Mistakes
| Mistake | Symptom | Fix |
|---|---|---|
| Reversed receiver and argument | Result holds the "other side" of the data | Read the call as "receiver without argument" and name results by meaning |
| Passing an array | `TypeError` | Wrap it: `a.difference(new Set(arr))` |
| Expecting `a` to change | `a` still has the removed elements | Assign the result: `a = a.difference(b)` |
| Removing look-alike objects | Nothing is removed | Compare by ID or share references |
| Assuming the subclass is kept | Missing subclass methods on the result | Wrap the result: `new TagSet(result)` |
Exercise
Given const granted = new Set(["read", "write", "share"]) and const required = new Set(["read", "write", "delete"]), write one expression that gives the permissions a user still needs, and state its contents.
Show answer
required.difference(granted) returns Set {"delete"}. The receiver is the set you want to check (required), and you take away what the user already has. Writing granted.difference(required) instead would return Set {"share"}, the extra permissions, which answers a different question.
Exercise
What does [...new Set([3, 1, 2]).difference(new Set([2, 7, 8, 9, 3]))] print, and does the engine call the argument's has or keys here?
Show answer
It prints [1]. The receiver has size 3 and the argument has size 5, so this.size <= other.size and the engine loops over the receiver, calling the argument's has for 3, 1, and 2. Only 1 is missing from the argument, so only 1 survives.
Exercise
A colleague writes const removed = oldTags.difference(newTags.values()) to find tags that were deleted. Why does this throw, and how should it be fixed?
Show answer
newTags.values() returns an iterator, not a set-like object. It has no numeric size and no has method, so the method throws a TypeError. Pass the set itself: oldTags.difference(newTags).