How are objects hashed within Map?

I have the following example code:

class NumberWrapper {
   data;
   constructor(data) {
       this.data = data;
   }
}

let x1 = new NumberWrapper(1);
let x2 = new NumberWrapper(1);

let map = new Map();

map.set(x1, "X1");

console.log(map.get(x1)); // "X1"
console.log(map.get(x2)); // undefined

If x1 and x2 have the same data, why is the hash different for the data structures? Is the hash based on the memory address?

If so, how can I get around this and possibly implement my hash function that the map uses instead?

Modifying x1 doesn’t result in any changes to x2, so I would hope that a map doesn’t treat them as the same object. I suspect that trying to work around this could result in very buggy behavior that’s hard to trace.

1 Like

You can stringify the objects. But at that point, it is just a string.

Objects do not have referential equality and I don’t think there would be much point allowing objects as keys if Map treated objects as being referentially equal.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.