Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does {} == {} equals false? [duplicate]

Short question about JavaScript. I tried to execute {} == {} in JavaScript and expected to get true, but it didn't and I want to understand why. Shouldn't {} == {} return true and {} === {} return false?

like image 496
Mario S Avatar asked May 22 '26 13:05

Mario S


1 Answers

Because == and === check if the two compared variables are references to the same object, not whether they are identical in value.

Thus a two variables internally referencing each other or a third variable are both == and ===, two new instances of an object are not.

To check if two objects are identical, you could JSON.stringify() them and check whether or not the results are the same.

Most common libraries for JavaScript contain a function to compare two objects, in vanilla JS you can make such a function for yourself:

Object.compare = function(obj1, obj2) {
  if (obj1 && obj2) return JSON.stringify(obj1) === JSON.stringify(obj2)
}

console.log(
    Object.compare({foo:"bar"}, {foo:"bar"})
);
like image 79
Luca Kiebel Avatar answered May 24 '26 03:05

Luca Kiebel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!