Enjoy 20% off all plans by following us on social media. Check out other promotions!
Quiz Questions

How do `Set`s and `Map`s handle equality checks for objects?

Topics
JAVASCRIPT
Edit on GitHub

TL;DR

Sets and Maps 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.

const set = new Set();
const obj1 = { a: 1 };
const obj2 = { a: 1 };
set.add(obj1);
set.add(obj2);
console.log(set.size); // Output: 2

How do Sets and Maps handle equality checks for objects?

Reference equality

In JavaScript, Sets and Maps 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.

const set = new Set();
const obj1 = { a: 1 };
const obj2 = { a: 1 };
set.add(obj1);
set.add(obj2);
console.log(set.size); // Output: 2

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.

const map = new Map();
const obj1 = { a: 1 };
const obj2 = { a: 1 };
map.set(obj1, 'value1');
map.set(obj2, 'value2');
console.log(map.size); // Output: 2
console.log(map.get(obj1)); // Output: 'value1'
console.log(map.get(obj2)); // Output: 'value2'

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 Sets and Maps, especially when dealing with complex data structures.

Further reading

Edit on GitHub