Search code examples
javascriptif-statementundefined

In if statement,undefined equals with false


I'm confused with the code below:

if(undefined){
   //code will not be executed
}

and

if(!undefined){
   //code will be executed
}

Is that mean the "undefined" equals with false?

Here the question related,but no one point above situation out.


Solution

  • It means that undefined is a falsy value, list of falsy values are:

    ""        // Empty string
    null      // null
    undefined // undefined, which you get when doing: var a;
    false     // Boolean false
    0         // Number 0
    NaN       // Not A Number eg: "a" * 2
    

    If you negate a falsy value you will get true:

    !""        === true
    !null      === true
    !undefined === true
    !0         === true
    !NaN       === true
    

    And when you nagate a truthy value you will get false:

    !"hello" === false
    !1       === false
    

    But undefined is not equal false:

    undefined === false // false
    undefined  == false // false
    

    And just for the fun if it:

    undefined == null // true