The following prints 'A' as expected, since the data type is different so the array is coaxed into a primitive form which is false
for empty arrays.
if ([] == false)
console.log('A');
else
console.log('B');
But then why the following code too prints 'A'?
if ([])
console.log('A');
else
console.log('B');
Why is
[] == false
is true
Because arrays behave oddly when compared to primitive values.
In particular, when you compare any non-boolean to a boolean, the boolean is handled as a number. Then, when you compare a number to an object the object is converted to a primitive - which stringifies the array before again comparing it to the number. Now, that string is converted to a number so that they can be compared:
[] == false
[] == 0
"" == 0
0 == 0
Similarly, you can try
[1] == true
[1] == 1
"1" == 1
1 == 1
or
[2] == true
[2] == 1
"2" == 1
2 == 1
but just
[]
evaluates to true?
Because any object is truthy.
The ==
operator forces a type cast. []
as boolean is false
. Why doesn't the same happen with eg. "a" == false
? Basically, the numeric value of []
is 0
, while the numeric value of "a"
is NaN
. Predictably, "0" == false
is true
:)
On the other hand, in the second case, you're basically just checking if []
exists ("isn't null"). There is no casting to boolean.
The first test returns true because of these equality rules :
If one of the operands is Boolean, the Boolean operand is converted to 1 if it is true and +0 if it is false.
If an object is compared with a number or string, JavaScript attempts to return the default value for the object. Operators attempt to convert the object to a primitive value, a String or Number value, using the valueOf and toString methods of the objects. If this attempt to convert the object fails, a runtime error is generated.
(and yes, you do have [].toString()==""
and thus []==0
)
The second test
if ([])
simply is passed because all objects are truish.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With