How do `Set`s and `Map`s handle equality checks for objects?
TL;DR
Sets and Maps in JavaScript handle equality checks for objects based on identity, not deep equality. Two object values are considered equal only when they refer to the same object. For example, if you add two different object literals with the same properties to a Set, they will be treated as distinct entries.
Reference equality
In JavaScript, Sets and Maps use object identity to determine whether two object values are the same. Two separately created objects remain distinct even when they contain equal-looking properties.
Example with Set
When you add objects to a Set, the Set will only consider them equal if they are the same object reference.
In this example, obj1 and obj2 have the same properties, but they are different object references. Therefore, the Set treats them as distinct entries.
Example with Map
Similarly, when you use objects as keys in a Map, the Map will only consider them equal if they are the same object reference.
In this example, obj1 and obj2 are different object references, so the Map treats them as different keys.
Practical implications
- Internally,
Sets andMaps compare values using the SameValueZero algorithm. For objects this reduces to reference equality, while for primitives it behaves like===except thatNaNis considered equal to itself. - If you need to check for deep equality (i.e., objects with the same properties and values), you will need to implement your own comparison logic or use a library like Lodash.
- Keep the original object reference when checking
Setmembership or looking up aMapkey.