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
?

- 2,247
- 3
- 15
- 32

- 85
- 1
- 9
-
9You could literally drop the title of this question into a web search and get your answer. – May 07 '18 at 11:59
2 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"})
);

- 9,790
- 7
- 29
- 44
-
So there isn't a function like .equals() in other languages in javascript that checks the content? – Mario S May 07 '18 at 12:04
-
No, but a lot of libraries include such a function; jQuery or underscore for example. – Luca Kiebel May 07 '18 at 12:04
-
2@MarioS the Object.Equals() I know from C# or Java also checks the object reference (unless you override it) – Pac0 May 07 '18 at 12:36
When comparing two objects with ===, the references will be checked.
These are not two references to the same obejcts, these are two different instances of an empty object.
When comparing with ==, there might be usually some coercion to some common type prior to comparison, following specific rules that are too complicated to be listed here.
But long story short, since you are compariong two objects, there won't be a different check.

- 21,465
- 8
- 65
- 74