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

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

    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
    }

提交回复
热议问题