In JS, it’s not clear if ‘0’ is truthy or falsy.
So, we have :
Boolean(‘0’) == true, because it’s a non-empty string.
But: ('0' == false)
The brain-itching starts from here :
(!'0' == false)
And then so…
('0' == !'0') // What ?!?
At the beginning, willing to store a websocket stream into a Mysql DB, I needed to convert each field from a string to its primitive type.
Using the double NOT operator to get booleans didn’t produce the result I was expecting :
(!!"1" == true) && (!!"0" == true)
Having my input string s, I finally came up with this working solution :
!!+s
Or this one : (s == '1')
2
Answers
In JavaScript 0 (zero) represent the
false
and 1 (one) representtrue
if(0===false)
it always returntrue
because this statement istrue
if("0"===false)
it always returnfalse
because this statement isfalse
because now0
is instring type
.Is
'0'
truthy?'0'
is truthy, because non-empty strings are truthy'0' == false
is truthy, because==
operator converts both operands to number first and then try to compare them.'0'
is converted to0
andfalse
is converted to0
(!'0' == false)
– here!'0'
is the same as!true
because a non-empty string is truthy('0' == !'0')
– first!'0'
is converted to!true
thenfalse
and then both operands are converted to number so0 == 0
is trueIf you want intuitive behaviour don’t use
==
. Use===
insteadConclusion:
'0'
is falsy, but==
operator converts strings to numbersAbout
(!!"1" == true) && (!!"0" == true)
:Isn’t it easier to use:
?