Let us guess two objects with same property:
var x = {a : \'some\'},
y = {a: \'some\'};
output:
x == y;
and x
All above comparison give
true
.
Right. You've specifically set p
and q
so they refer to the same object.
With object references, both ==
(if both sides are object references) and ===
will check to see if the references are pointing to the same object. If you have two identical, but separate, objects, both will always be false
.
So for example:
var a = {}; // a points to an object
var b = {}; // b points to a _different_ object
console.log(a === b); // "false"
console.log(a == b); // "false"
var c = {}; // c points to an object
var d = c; // d points to _the same_ object
console.log(c === d); // "true"
console.log(c == d); // "true"
The content of the objects is irrelevant, it's the identity of them that's being checked.
Note that this is not true if you use ==
and only one side is an object reference (e.g., the other side is a number, a primitive string, undefined
, etc.). In that case, the object reference will be asked to convert itself (to either a string or a number, depending on what the other thing is), and then the converted result will be used for the comparison. This can lead to surprising behavior (for instance, "2" == [[[[[2]]]]]
is true
because the array is asked to turn itself into a string, which it does via join
[which will ask its element to convert itself to a string, and so on], and you end up with "2"
on the right-hand side). So I typically prefer ===
("strict equality" over ==
("loose equality").