Seems like the following code should return a true, but it returns false.
var a = {};
var b = {};
console.log(a==b); //returns false
console.log(a===b); //
How does this make sense?
Because "equality" of object references, in terms of the ==
and ===
operators, is purely based on whether the references refer to the same object. This is clearly laid out in the abstract equality comparison algorithm (used by ==
) and the strict equality comparison algorithm (used by ===
).
In your code, when you say a==b
or a===b
, you're not comparing the objects, you're comparing the references in a
and b
to see if they refer to the same object. This is just how JavaScript is defined, and in line with how equality operators in many (but not all) other languages are defined (Java, C# [unless the operator is overridden, as it is for string], and C++ for instance).
JavaScript has no inbuilt concept of equivalence, a comparison between objects that indicates whether they're equivalent (e.g., have the same properties with the same values, like Java's Object#equals
). You can define one within your own codebase, but there's nothing intrinsic that defines it.