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

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

    Since there is no single complete and correct answer, I will try to summarize:

    In general, the expression:

    if (typeof(variable) != "undefined" && variable != null)
    

    cannot be simplified, because the variable might be undeclared so omitting the typeof(variable) != "undefined" would result in ReferenceError. But, you can simplify the expression according to the context:

    If the variable is global, you can simplify to:

    if (window.variable != null)
    

    If it is local, you can probably avoid situations when this variable is undeclared, and also simplify to:

    if (variable != null)
    

    If it is object property, you don't have to worry about ReferenceError:

    if (obj.property != null)
    
    0 讨论(0)
  • 2020-11-22 16:18

    Open the Developer tools in your browser and just try the code shown in the below image.

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

    Checking null with normal equality will also return true for undefined.

    if (window.variable == null) alert('variable is null or undefined');

    JS Equality

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

    You can just check if the variable has a value or not. Meaning,

    if( myVariable ) {
    //mayVariable is not :
    //null
    //undefined
    //NaN
    //empty string ("")
    //0
    //false
    
    }
    

    If you do not know whether a variable exists (that means, if it was declared) you should check with the typeof operator. e.g.

    if( typeof myVariable !== 'undefined' ) {
        // myVariable will get resolved and it is defined
    }
    
    0 讨论(0)
  • 2020-11-22 16:19

    You must define a function of this form:

    validate = function(some_variable){
        return(typeof(some_variable) != 'undefined' && some_variable != null)
    }
    
    0 讨论(0)
  • 2020-11-22 16:19

    In ES5 or ES6 if you need check it several times you cand do:

    const excluded = [null, undefined, ''];
    
    if (!exluded.includes(varToCheck) {
      // it will bee not null, not undefined and not void string
    }

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