Is there a reason as to why these statements evaluate to true?
0 == [0];
1 == [1];
5 == [5];
5000 == [5000];
1000000 == [1000000];
So basically any number equals itself wrapped in an array? What's the logic behind this?
Is there a reason as to why these statements evaluate to true?
0 == [0];
1 == [1];
5 == [5];
5000 == [5000];
1000000 == [1000000];
So basically any number equals itself wrapped in an array? What's the logic behind this?
That's because the non-strict equality operator coerces both its operands to strings in this case, and the string representation of an array is the elements it contains, delimited by commas:
>>> [1, 5].toString()
"1,5"
Since the arrays in your question only contain one element, their string representation is the same as their element's:
>>> [5000].toString()
"5000"
[0]
is an array with one element "0". So 0 == [0]
would be the equivalent of doing:
0 == myArray(0)
in another language. Where myArray(0) returns the value at the index 0
, which in this case would be 0.
That's my understanding of JavaScript arrays. Someone else may want to jump in and correct me if I'm wrong.
Because == does not compare type of the variable, and === does compare type of the variable, so:
0 == [0] //true
0 === [0] // false
In the same case:
0 == '0' //true
0 === '0' //false
One reason behind this is the operator used is "==" which compares only compares values and not data types as in 1=="1" is true.