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

前端 未结 24 2193
悲&欢浪女
悲&欢浪女 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条回答
  •  Happy的楠姐
    2020-11-22 16:35

    I think the most efficient way to test for "value is null or undefined" is

    if ( some_variable == null ){
      // some_variable is either null or undefined
    }
    

    So these two lines are equivalent:

    if ( typeof(some_variable) !== "undefined" && some_variable !== null ) {}
    if ( some_variable != null ) {}
    

    Note 1

    As mentioned in the question, the short variant requires that some_variable has been declared, otherwise a ReferenceError will be thrown. However in many use cases you can assume that this is safe:

    check for optional arguments:

    function(foo){
        if( foo == null ) {...}
    

    check for properties on an existing object

    if(my_obj.foo == null) {...}
    

    On the other hand typeof can deal with undeclared global variables (simply returns undefined). Yet these cases should be reduced to a minimum for good reasons, as Alsciende explained.

    Note 2

    This - even shorter - variant is not equivalent:

    if ( !some_variable ) {
      // some_variable is either null, undefined, 0, NaN, false, or an empty string
    }
    

    so

    if ( some_variable ) {
      // we don't get here if some_variable is null, undefined, 0, NaN, false, or ""
    }
    

    Note 3

    In general it is recommended to use === instead of ==. The proposed solution is an exception to this rule. The JSHint syntax checker even provides the eqnull option for this reason.

    From the jQuery style guide:

    Strict equality checks (===) should be used in favor of ==. The only exception is when checking for undefined and null by way of null.

    // Check for both undefined and null values, for some important reason. 
    undefOrNull == null;
    

提交回复
热议问题