This returns true:
[] == false
But here, alert is called:
if([]){ alert('empty array is true here'); }
Can you explain why?
This returns true:
[] == false
But here, alert is called:
if([]){ alert('empty array is true here'); }
Can you explain why?
According to section 11.9.3 of the ECMAScript® Language Specification, any ==
comparison is done as follows:
In the first step, ToNumber()
is applied to false
and yields Number(0)
. In the second step, rule #9 applies ToPrimitive()
to the empty array and yields ""
which, cast to a numeric value, becomes Number(0)
as well.
Additionally section 9.2 says this about using an object in an expression:
The abstract operation
ToBoolean
converts its argument to a value of type Boolean according to this table:
this is because ==
in JS forces conversion and if one type can be converted to another the return value is true
and here because []
cant be changed or compared with bool it is false
where as if([])
checks for null
and undefined
values and because [] is neither null or undefined it is returning true
check this Which equals operator (== vs ===) should be used in JavaScript comparisons?