Reputation: 1359
I have the following code
console.log(typeof id1, typeof id2)
console.log(id1, id2)
if (id1 === id2) {
return true
}else{
return false
}
If I execute the following code I end up with id1 of type Object and the same for id2. when I compare them with === it returns false even thought they are of the same type. I know that if I use == this will be true because type checking is not enforced. Can someone clarify why it returns false with === operator even though the type is the same.
The following is the result printed using console.log
object , object
5e90603e7f0d251cab9253c6 , 5e90603e7f0d251cab9253c6
The ids are mongoose ObjectId
Upvotes: 0
Views: 239
Reputation: 1244
Because objects in javascript are reference variables, whats happening there is the memory allocation are the one being compared.
If your comparing objectIds what you can do is:
id1.toString() === id2.toString()
Upvotes: 3