Consider empty JavaScript array:
var a = [];
alert(a == false); // shows true
alert(!a); // shows false!
How to explain this? What are the
When comparing an object to a primitive value via the ==
operator, the object coerces into an primitive value itself (number or string). In this case []
coerces into 0
, then false
coerces into 0
:
[] == false
0 == false
0 == 0
which is true.
The !
operator coerces into boolean and then inverts the value. []
into boolean is true
(like with any object). Then invert to become false
![]
!true
false