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

前端 未结 24 1929
悲&欢浪女
悲&欢浪女 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:32

    In order to understand, Let's analyze what will be the value return by the Javascript Engine when converting undefined , null and ''(An empty string also). You can directly check the same on your developer console.

    You can see all are converting to false , means All these three are assuming ‘lack of existence’ by javascript. So you no need to explicitly check all the three in your code like below.

    if (a === undefined || a === null || a==='') {
        console.log("Nothing");
    } else {
        console.log("Something");
    }
    

    Also I want to point out one more thing.

    What will be the result of Boolean(0)?

    Of course false. This will create a bug in your code when 0 is a valid value in your expected result. So please make sure you check for this when you write the code.

    0 讨论(0)
  • 2020-11-22 16:33

    Firstly you have to be very clear about what you test. JavaScript has all sorts of implicit conversions to trip you up, and two different types of equality comparator: == and ===.

    A function, test(val) that tests for null or undefined should have the following characteristics:

     test(null)         => true
     test(undefined)    => true
     test(0)            => false
     test(1)            => false
     test(true)         => false
     test(false)        => false
     test('s')          => false
     test([])           => false
    

    Let's see which of the ideas here actually pass our test.

    These work:

    val == null
    val === null || val === undefined
    typeof(val) == 'undefined' || val == null
    typeof(val) === 'undefined' || val === null
    

    These do not work:

    typeof(val) === 'undefined'
    !!val
    

    I created a jsperf entry to compare the correctness and performance of these approaches. Results are inconclusive for the time being as there haven't been enough runs across different browsers/platforms. Please take a minute to run the test on your computer!

    At present, it seems that the simple val == null test gives the best performance. It's also pretty much the shortest. The test may be negated to val != null if you want the complement.

    0 讨论(0)
  • 2020-11-22 16:34

    this is the only case in which == and != should be used:

    if (val == null) console.log('val is null or undefined')
    
    if (val != null) console.log('val is neither null nor undefined')
    
    0 讨论(0)
  • 2020-11-22 16:34

    Both values can be easily distinguished by using the strict comparison operator:

    Working example at:

    http://www.thesstech.com/tryme?filename=nullandundefined

    Sample Code:

    function compare(){
        var a = null; //variable assigned null value
        var b;  // undefined
        if (a === b){
            document.write("a and b have same datatype.");
        }
        else{
            document.write("a and b have different datatype.");
        }   
    }
    
    0 讨论(0)
  • 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;
    
    0 讨论(0)
  • 2020-11-22 16:35

    If the purpose of the if statement is to check for null or undefined values before assigning a value to a variable, you can make use of the Nullish Coalescing Operator, is finally available on JavaScript, though browser support is limited. According to the data from caniuse, only 48.34% of browsers are supported (as of April 2020).

    const a = some_variable ?? '';
    

    This will ensure that the variable will be assigned to an empty string (or any other default value) if some_variable is null or undefined.

    This operator is most suited for your use case, as it does not return the default value for other types of falsy value such as 0 and ''.

    0 讨论(0)
提交回复
热议问题