How to check for an undefined or null variable in JavaScript?

前端 未结 24 1946
悲&欢浪女
悲&欢浪女 2020-11-22 15:55

We are frequently using the following code pattern in our JavaScript code

if (typeof(some_variable) != \'undefined\' && some_variable != null)
{
             


        
24条回答
  •  逝去的感伤
    2020-11-22 16:11

    This is an example of a very rare occasion where it is recommended to use == instead of ===. Expression somevar == null will return true for undefined and null, but false for everything else (an error if variable is undeclared).

    Using the != will flip the result, as expected.

    Modern editors will not warn for using == or != operator with null, as this is almost always the desired behavior.

    Most common comparisions:

    undeffinedVar == null     // true
    obj.undefinedProp == null // true
    null == null              // true
    0 == null                 // false
    '0' == null               // false
    '' == null                // false
    

    Try it yourself:

    let undefinedVar;
    console.table([
        { test : undefinedVar,     result: undefinedVar     == null },
        { test : {}.undefinedProp, result: {}.undefinedProp == null },
        { test : null,             result: null             == null },
        { test : false,            result: false            == null },
        { test : 0,                result: 0                == null },
        { test : '',               result: ''               == null },
        { test : '0',              result: '0'              == null },
    ]);
    

提交回复
热议问题