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

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

提交回复
热议问题