How to check if a variable is not null?

前端 未结 9 1083
太阳男子
太阳男子 2020-11-28 17:47

I know that below are the two ways in JavaScript to check whether a variable is not null, but I’m confused which is the best practice to use.

Should I d

9条回答
  •  被撕碎了的回忆
    2020-11-28 18:15

    Sometimes if it was not even defined is better to be prepared. For this I used typeof

    if(typeof(variable) !== "undefined") {
        //it exist
        if(variable !== null) {
            //and is not null
        }
        else {
            //but is null
        }
    }
    else {
        //it doesn't
    }
    

提交回复
热议问题