How to check a not-defined variable in JavaScript

后端 未结 14 958
陌清茗
陌清茗 2020-11-22 14:23

I wanted to check whether the variable is defined or not. For example, the following throws a not-defined error

alert( x );

How can I cat

14条回答
  •  暖寄归人
    2020-11-22 15:14

    An even easier and more shorthand version would be:

    if (!x) {
       //Undefined
    }
    

    OR

    if (typeof x !== "undefined") {
        //Do something since x is defined.
    }
    

提交回复
热议问题