How to check a not-defined variable in JavaScript

后端 未结 14 1006
陌清茗
陌清茗 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 14:59

    The void operator returns undefined for any argument/expression passed to it. so you can test against the result (actually some minifiers change your code from undefined to void 0 to save a couple of characters)

    For example:

    void 0
    // undefined
    
    if (variable === void 0) {
        // variable is undefined
    }
    

提交回复
热议问题