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

前端 未结 24 2221
悲&欢浪女
悲&欢浪女 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)
    

提交回复
热议问题