Why both
[] == false
and
![] == false
are true?
The === operator is your friend. Never use the == operator; it will bite you, as you can see.
An empty list, []
must be considered a "falsey", however in ![]
the ! is then converting the operation to check for an object reference, where a non-null is not considered a "falsey".
Before [] is compared to false, it is coerced to a string which is coerced to a number, the empty string in the case of the empty array. The empty string coerces to 0 which is the same value that false coerces to numerically.
Use === instead of == to avoid this problem
These other arrays are also falsey:
['']
[[[]]]
(function () { var arr = []; arr[0] = arr; })()
[0]
['-0.0']