Sub topic 8
Objects in Sets: Reference Equality
This chapter assumes you know how to create a Set, that you have seen union, intersection, and difference in earlier chapters, and that you understand the basic difference between primitive values and object references. Here the focus is on one question: when do two elements count as "the same" inside a Set method?
Numbers and strings behave the way you expect. Objects often don't. Two objects that look identical can be treated as different elements, and that causes quiet bugs: empty intersections, differences that remove nothing, and unions that hold apparent duplicates.
How Set Methods Compare Elements
Every Set method uses the same rule the Set constructor and has use. That rule is SameValueZero, the comparison algorithm JavaScript uses for Set and Map membership. It works almost exactly like ===, with two differences:
NaNequalsNaN. With===,NaN === NaNisfalse.-0and+0count as the same value, as they do with===.
For objects, SameValueZero only checks whether two values point to the same object in memory. It never looks at their properties.
Here is the primitive side of the rule in action:
const a = new Set([1, "1", NaN, 0]);
const b = new Set([1, NaN, -0]);
console.log([...a.intersection(b)]); // [1, NaN, 0]
console.log(a.has("1"), b.has("1")); // true falseThe number 1 and the string "1" are different elements because their types differ. NaN matches NaN, and 0 matches -0. Results never contain -0. The Set methods normalize it to +0, the same way add does.
Objects Match Only by Reference
Now compare objects. The spine example shows the core behavior:
const x = { id: 1 };
const a = new Set([x, { id: 2 }]);
const b = new Set([x, { id: 2 }]);
console.log(a.intersection(b).size); // 1 (only the shared reference x)Each { id: 2 } literal creates a new object. Set a and set b each hold a different object that happens to have the same shape. The variable x holds one object, and both sets store that same reference, so only x survives the intersection.
The same rule applies to every kind of object:
const arrays = new Set([[1, 2]]);
console.log(arrays.has([1, 2])); // false
const dates = new Set([new Date("2026-01-01")]);
console.log(dates.has(new Date("2026-01-01"))); // false
const fn = () => 1;
const fns = new Set([fn]);
console.log(fns.has(fn)); // true
console.log(fns.has(() => 1)); // falseArrays, Dates, functions, Maps, and class instances are all objects, so all of them compare by reference.
What This Does to Each Method
Reference equality changes each method's result in a predictable way when your data holds lookalike objects instead of shared references.
| Method | What you expect with lookalike objects | What actually happens |
|---|---|---|
| `union` | Duplicates merged | Both copies kept, so the size grows |
| `intersection` | Matching objects kept | Lookalikes dropped, often leaving an empty result |
| `difference` | Matching objects removed | Nothing removed; the receiver's objects all remain |
| `symmetricDifference` | Only unmatched objects | Every lookalike from both sides appears |
| `isSubsetOf` | `true` for equal contents | `false` unless the references are shared |
| `isDisjointFrom` | `false` when contents overlap | `true` even though the data "overlaps" |
const cart = new Set([{ sku: "A1" }, { sku: "B2" }]);
const removed = new Set([{ sku: "B2" }]);
const remaining = cart.difference(removed);
console.log(remaining.size); // 2, nothing was removed
console.log(cart.isDisjointFrom(removed)); // trueResults Share References With the Inputs
Set methods return a new Set, but they do not copy the elements. The result holds the same object references as the inputs. In other words, the copy is shallow.
const ana = { name: "Ana", role: "viewer" };
const team = new Set([ana]);
const everyone = team.union(new Set([{ name: "Ben", role: "admin" }]));
ana.role = "editor";
const anaInResult = [...everyone].find((u) => u.name === "Ana");
console.log(anaInResult.role); // "editor"
console.log(anaInResult === ana); // trueThe Set structure is independent: adding to everyone doesn't change team. The objects inside are shared, so a mutation through any reference shows up everywhere. Mutating an object also never changes its membership. A Set does not re-check an element after you change its properties, because membership depends only on identity.
Working Around Reference Equality
When you need to compare objects by their content, change what goes into the Set. These are the usual approaches, roughly in the order you should reach for them.
Approach 1: Compare Primitive Keys
Most records have a natural primitive identifier, such as an ID, email, or SKU. Build Sets of those keys, run the Set method on the keys, then map the keys back to objects through a Map.
const usersA = [
{ id: 1, name: "Ana" },
{ id: 2, name: "Ben" },
];
const usersB = [
{ id: 2, name: "Ben" },
{ id: 3, name: "Cy" },
];
const byIdA = new Map(usersA.map((u) => [u.id, u]));
const idsA = new Set(byIdA.keys());
const idsB = new Set(usersB.map((u) => u.id));
const sharedIds = idsA.intersection(idsB);
const shared = [...sharedIds].map((id) => byIdA.get(id));
console.log(shared); // [{ id: 2, name: "Ben" }]This approach is the clearest one, and it keeps every comparison on fast primitive lookups. You also decide which side's objects come back. Here the objects come from usersA. If the two sides can hold different versions of a record, looking up from the side you trust matters.
You can wrap the pattern in a reusable helper that takes a key function:
function intersectionBy(a, b, keyOf) {
const bKeys = new Set([...b].map(keyOf));
return new Set([...a].filter((item) => bKeys.has(keyOf(item))));
}
function differenceBy(a, b, keyOf) {
const bKeys = new Set([...b].map(keyOf));
return new Set([...a].filter((item) => !bKeys.has(keyOf(item))));
}
const cart = new Set([{ sku: "A1" }, { sku: "B2" }]);
const removed = new Set([{ sku: "B2" }]);
console.log([...differenceBy(cart, removed, (i) => i.sku)]); // [{ sku: "A1" }]
console.log(intersectionBy(cart, removed, (i) => i.sku).size); // 1These helpers accept any iterable for a and b, including arrays. They keep a's order and return a's objects.
Approach 2: Share References From One Source
If every part of your program gets its objects from one place, such as a store or cache keyed by ID, then equal records are the same object, and the Set methods work directly. This is called interning: you keep one canonical object per distinct value and always hand out that object.
const pointCache = new Map();
function point(x, y) {
const key = `${x},${y}`;
let p = pointCache.get(key);
if (!p) {
p = Object.freeze({ x, y });
pointCache.set(key, p);
}
return p;
}
const visited = new Set([point(0, 0), point(1, 2)]);
const targets = new Set([point(1, 2), point(5, 5)]);
console.log(visited.intersection(targets).size); // 1
console.log(point(1, 2) === point(1, 2)); // trueObject.freeze matters here. A canonical object must not change, or point(1, 2) could end up returning an object whose x is no longer 1. The trade-off is memory: the cache keeps every point alive unless you clear it.
Approach 3: Serialize to Strings
For small value objects with no natural ID, you can turn each object into a string and put the strings in the Set.
const a = new Set([{ x: 1, y: 2 }, { x: 3, y: 4 }].map((o) => JSON.stringify(o)));
const b = new Set([{ x: 1, y: 2 }].map((o) => JSON.stringify(o)));
console.log([...a.intersection(b)]); // ['{"x":1,"y":2}']
console.log(JSON.stringify({ x: 1, y: 2 }) === JSON.stringify({ y: 2, x: 1 })); // falseThe last line shows the catch. JSON.stringify follows property insertion order, so objects with the same content written in a different order produce different strings. It also drops undefined values and functions, turns NaN into null, and throws on BigInt. Use serialization only when you control how the objects are built. A hand-written key such as ` ${o.x},${o.y} ` is usually safer.
Choosing an Approach
| Situation | Best approach |
|---|---|
| Records have a stable ID | Compare primitive keys |
| Objects already come from one store | Use the objects directly |
| Many small immutable value objects | Interning |
| Quick script, objects built the same way | Serialize to strings |
| Need full deep equality | Key function that builds a canonical string |
Common Mistakes
- Expecting
new Set([{ id: 1 }]).has({ id: 1 })to betrue. It is alwaysfalse, because the literal creates a new object. - Diffing a fresh API response against cached objects. Every element looks new, so
differenceremoves nothing. - Treating the result as a deep copy. Mutating an object in the result also changes it in the input Sets.
- Mixing key types, for example numeric IDs on one side and string IDs from a URL on the other.
1and"1"never match. Convert one side withNumberorStringfirst. - Serializing objects whose properties were added in different orders, then wondering why the strings don't match.
Exercise
Predict the output of this code, then explain each line. const tag = { name: "js" }; const a = new Set([tag, { name: "css" }]); const b = new Set([{ name: "js" }, { name: "css" }, tag]); console.log(a.intersection(b).size); console.log(a.isSubsetOf(b)); console.log(b.difference(a).size);
Show answer
The output is 1, false, 2. Only the tag reference appears in both sets, so the intersection has one element. a holds its own { name: "css" } object, which b does not contain, so a is not a subset of b. b.difference(a) removes only tag, leaving b's two literal objects { name: "js" } and { name: "css" }.
Exercise
You have two arrays of order objects, yesterday and today, each shaped like { orderId: "A-17", total: 40 }. They come from separate API calls. Write code that produces an array of the order objects from today whose orderId did not appear in yesterday, using Set.prototype.difference.
Show answer
Index today's orders by ID, take the difference of the ID sets, then map back: const todayById = new Map(today.map((o) => [o.orderId, o])); const newIds = new Set(todayById.keys()).difference(new Set(yesterday.map((o) => o.orderId))); const newOrders = [...newIds].map((id) => todayById.get(id)); Comparing the objects directly would fail, because the two API calls produce distinct objects, so every order would look new.
Exercise
A teammate interns points with a cache, but returns plain unfrozen objects. Later some code runs p.x += 1 on a point it got from the cache. What goes wrong with later Set comparisons?
Show answer
The cached object is shared, so the mutation changes it for everyone. A later call point(1, 2) returns the object stored under the key "1,2", which now has x equal to 2. Sets that should hold the point (1, 2) now hold an object whose content is (2, 2), and a fresh point(2, 2) creates a different object that won't match it. Freezing canonical objects prevents this.