How do `Set`s and `Map`s handle equality checks for objects?
TL;DR
Set
s and Map
s in JavaScript handle equality checks for objects based on reference equality, not deep equality. This means that two objects are considered equal only if they reference the same memory location. For example, if you add two different object literals with the same properties to a Set
, they will be treated as distinct entries.
How do Set
s and Map
s handle equality checks for objects?
Reference equality
In JavaScript, Set
s and Map
s use reference equality to determine if two objects are the same. This means that two objects are considered equal only if they reference the same memory location.
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
- 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.
- Be mindful of object references when using
Set
s andMap
s, especially when dealing with complex data structures.