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

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

    whatever yyy is undefined or null, it will return true

    if (typeof yyy == 'undefined' || !yyy) {
        console.log('yes');
    } else {
        console.log('no');
    }
    

    yes

    if (!(typeof yyy == 'undefined' || !yyy)) {
        console.log('yes');
    } else {
        console.log('no');
    }
    

    no

提交回复
热议问题