Search code examples
javascriptcastingtruthiness

Javascript Truthy / Falsy Operation


I have a question regarding javascript truthy / falsy

As far as I know, any non-zero number including negative numbers is truthy. But if this is the case then why

-1 == true //returns false

But also

-1 == false //returns false

Can someone shed some light? I would appreciate it.


Solution

  • When using the == operator with a numeric operand and a boolean operand, the boolean operand is first converted to a number, and the result is compared with the numeric operand. That makes your statements the equivalent of:

    -1 == Number(true)
    

    and

    -1 == Number(false)
    

    Which in turn are

    -1 == 1
    

    and

    -1 == 0
    

    Which shows why you're always seeing a false result. If you force the conversion to happen to the numeric operand, you get the result you're after:

    Boolean(-1) == true //true