Corresponding array in JavaScript
An array versus another array is not the same because they point to different memory addresses.
But array versus string for equality ( b == c
), passes array to string; effectively, it does something similar to:
b.toString() === c
But with identity matching ( ===
) it will also check the type of both variables, in which case it b === c
will render as false
.
source to share
Obviously, arrays are passed in comma-delimited strings compared to strings. [UPDATE: As Sawant correctly points out, it invokes an array method toString()
.] But arrays are simply arrays compared to arrays, and only the same instance will be equal to itself.
This is a good reason why you should always use ===
and never use ==
.
If you need to compare arrays with the elements they contain, use a function isEqual
from the lodash library.
source to share
-
Comparing two objects (array), they are not the same!
a==b // false
-
Comparison of two strings, because an array versus a string will be passed to a string.
b==c // true
-
Same as 2.
c==a // true
When you compare with ==
, the interpreter will try to make the left and right sides the same type.
First it will format it to string -> number -> boolean
So, for example, comparing ![] == []
.
-
![] == []
-
false == []
-
false == ""
-
false == false
These are the steps the interpreter must follow in order to come up with:
![] == [] // true
Because of all this, just use the operator ===
and it will be much faster.
source to share