CodePark/ questions / Value objects, equality & invariants
START PRACTICINGPRACTICE
Backend question · Object-oriented programming › Value objects, equality & invariants

What does this print?

class Money {
  constructor(amount, currency) {
    this.amount = amount;
    this.currency = currency;
  }
}
const prices = new Set([new Money(5, "EUR"), new Money(5, "EUR")]);
console.log(prices.size, new Money(5, "EUR") === new Money(5, "EUR"));
2 false

It prints 2 false. For objects, === and Set compare identity: "is this the same object in memory?". They do not compare the values inside. Two new calls make two different objects.

"
1 false" is tempting if you expect Set to be smarter than ===. It is not: Set and Map keys use the same identity rule. For value objects, write an equals(other) method. To use them as keys, use a string key such as "5:EUR".