skip to Main Content

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


  1. In JavaScript 0 (zero) represent the false and 1 (one) represent true

    if(0===false) it always return true because this statement is true
    if("0"===false) it always return false because this statement is false because now 0 is in string type .

    Login or Signup to reply.
  2. 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'
    

    ?

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search