Search code examples
javascriptvariablessyntaxoperators

Why does an exclamation mark before a variable return 'true' if the variable value is zero?


I looked a lot, but I couldn't find an answer for this especific case.

Why does this expression return true?

let variable = 0
!variable // true

I understand that the ! mark checks if a value is null or undefined, but in this case variable is defined. This is tricking me. Isn't 0 really considered a valid value?


Solution

  • ! is known as the logical NOT operator. It reverses the boolean result of the operand (or condition)

    0 is also considered as the boolean false, so when you use !variable you are using the logical operator and saying it to change the value of the variable to its opposite, that in boolean is true

    0 == false == !1 == !true

    1 == true == !0 == !false

    in Javascript are considered false: false, null, undefined, "", 0, NaN

    are considered true: true, 1, -0, "false". <- the last one is a not empty string, so its true

    if( false || null || undefined || "" || 0 || NaN) //never enter
    if( true && 1 && -1 && "false") //enter
    

    https://developer.mozilla.org/en-US/docs/Glossary/Falsy