Reputation: 10512
Assuming Array
was not overwritten, why the following comparisons output false?
[] === new Array()
> false
[] === []
> false
Upvotes: 0
Views: 238
Reputation: 156
In JavaScript, when you use ==
and ===
on an object (an array is just an object, []
is just syntactic sugar), return true
only if both operands refer to the exact same object, but not if they refer to 2 different, even identical objects.
For Example:
js> var x = []
js> var y = []
js> x == y
false
js> x = y
js> x == y
true
Think of it as the difference between two people talking about the same person, versus two people respectively talking about each of two twins.
Upvotes: 0
Reputation: 147363
The ===
operator uses the strict equality comparison algorithm, which says at step 7:
Return true if x and y refer to the same object. Otherwise, return false.
So if a and b reference an object, then a === b
only if a and b reference the same object (noting that Arrays are Objects).
Upvotes: 1
Reputation: 150020
Whether using the equality ==
operator or the strict equality ===
operator, if the operands are objects the result will be true only if both operands refer to the same object.
Your code creates two distinct arrays, both empty, so intuitively they might seem equal but that is not how the equals operators work.
Similarly something like [1,2,3] === [1,2,3]
will be false. Again it is easy to think they should be equal, but the comparison is testing whether the arrays are the same array, not whether all of the elements in the array are equal.
On the other hand x === y
will be true if both x
and y
refer to the same array.
For more information: https://developer.mozilla.org/en/JavaScript/Reference/Operators/Comparison_Operators
Upvotes: 1
Reputation: 14777
The objects are different, as in they are different segments of memory. For example:
var a = [],
b = [];
a === b; // false
typeof a === typeof b; // true
Note: the typeof statements are going to return "object" not "array". There are much better ways of determining if an object is an array. But this suffices for the explanation.
Upvotes: 1
Reputation:
You're comparing two unique Array objects for identity, not content.
Upvotes: 1