if("0") {} being equivalent to if(false) {} still gives me nightmares even though I've stopped using PHP for at least 6 years now :)
!""
into the browser console just to be sure, during code reviews :D "0" == false : true
"" == false : true
" " == false : true
"1" == false : false
!"0" : false
!"" : true
!" " : false
!"1" : false
In PHP: "0" == false : true
"" == false : true
" " == false : true
"1" == false : false
!"0" : true
!"" : true
!" " : false
!"1" : false
Honestly the only way to remain sane in either, but especially if you use both, is to always use === and never use boolean logic (!) when a string could be involved.!someValue is useful only for:
- booleans, including optional booleans (which is why every bool flag should default to false)
- undefined, null (falsy), or object/function (truthy)
It's nice for the second variant to also cover falsy NaN or things like this, for example for forms.
I guess that's where
!!""===false
comes from.But it's this exact case that keeps tripping me up.
What about empty arrays?
Per my original comment, now I'd have to look up if
![]
is false in PHP, or just
empty([]) === true.
So yea I agree, and extend your case to PHP "arrays" (in JS,
!![] === true
is trueIt's the string ones (in particular that in addition to the empty string, "0" specifically is the only other falsy string) that tend to catch people out.
if ($input) {}
It'll work through every test case you try, and then someone enters a 0 into the field and it's also unexpectedly considered empty.