Search code examples
javascriptoperator-keyword

In javascript, is "0" falsy or truthy?


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')


Solution

  • 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 to 0 and false is converted to 0

    (!'0' == false) - here !'0' is the same as !true because a non-empty string is truthy

    ('0' == !'0') - first !'0' is converted to !true then false and then both operands are converted to number so 0 == 0 is true

    If you want intuitive behaviour don't use ==. Use === instead

    Conclusion:

    '0' is falsy, but == operator converts strings to numbers

    About (!!"1" == true) && (!!"0" == true):

    Isn't it easier to use:

    const s = '1'
    const boolean = s === '1'
    

    ?