Let us guess two objects with same property:
var x = {a : 'some'},
y = {a: 'some'};
output:
x == y; and x === y; both give false
Similarly for two array,
var p = [1, 2, 3],
q = [1,2,3];
p == q and p === q both give false.
But for if I do following:
var x = y = {a: 'some'};
var p = q = [1, 2, 3];
All above comparison give true.
Why Javascript do such thing? Explain Please.
Right. You’ve specifically set
pandqso 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 befalse.So for example:
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]]]]]istruebecause the array is asked to turn itself into a string, which it does viajoin[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”).