Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array equality / inequality

Tags:

javascript

Can anyone explain why these JavaScript Array inequality comparisons evaluate to true?

[""] !== [""]

[1] !== [1]

[] !== []


[""] != [""]

[1] != [1]

[] != []
like image 322
Norman Cousineau Avatar asked Jul 10 '13 14:07

Norman Cousineau


People also ask

Can you use == to compare arrays?

equals() to compare two arrays is often misconstrued as content equality, and because a better alternative exists in the use of reference equality operators, the use of the Object. equals() method to compare two arrays is disallowed.

Does == work for arrays in JavaScript?

Javascript arrays are objects and you can't simply use the equality operator == to understand if the content of those objects is the same.

How do you check if two arrays are equality?

The Arrays. equals() method checks the equality of the two arrays in terms of size, data, and order of elements. This method will accept the two arrays which need to be compared, and it returns the boolean result true if both the arrays are equal and false if the arrays are not equal.


1 Answers

=== is strict equality.
When comparing objects, it will only return true if both sides refer to the same object.

[] and [] are two different (though equivalent) objects, so it returns false.


== is loose equality.

It will attempt to coerce both operands to the same type, as described in the spec.

However, it too compares objects by referential identity.

like image 185
SLaks Avatar answered Sep 27 '22 21:09

SLaks