Reputation: 1
Background:
I am new to typescript and try to work with Map. I have a question about the equality of maps. I searched for it, but I didn't find out.
Problem:
I created two simple Maps in TypeScript 3.5.1 and try to use === operator to see did they equal or not, but the result is odd for me.
Code:
const myMap1: Map<string, number> = new Map([['a', 1]]);
const myMap2: Map<string, number> = new Map().set('a', 1);
console.log(myMap1 === myMap2);
// console output => false
Where:
I ran this code in:
https://typescript-play.js.org/#code
You can see my code here:
Result:
false
Expected:
true
Question: Why these two maps are different?
Upvotes: 0
Views: 112
Reputation: 85062
===
with two objects (including two Maps) does a reference equality check. In other words, it's seeing if the two objects are literally the same object. It does not check what they contain to see if all their properties are the same.
const a = new Map();
const a2 = a;
const b = new Map();
console.log(a === a2); // true
console.log(a === b); // false
const c = {};
const c2 = c;
const d = {};
console.log(c === c2); // true
console.log(c === d); // false
If you want to check whether the contents of two maps are the same, then you'll need to implement that yourself, and you'll also need to decide what counts as equal. Do they have to be in the same order in both maps? This will have a different implementation than if the order doesn't matter.
Upvotes: 2