How to check a not-defined variable in JavaScript

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

    The accepted answer is correct. Just wanted to add one more option. You also can use try ... catch block to handle this situation. A freaky example:

    var a;
    try {
        a = b + 1;  // throws ReferenceError if b is not defined
    } 
    catch (e) {
        a = 1;      // apply some default behavior in case of error
    }
    finally {
        a = a || 0; // normalize the result in any case
    }
    

    Be aware of catch block, which is a bit messy, as it creates a block-level scope. And, of course, the example is extremely simplified to answer the asked question, it does not cover best practices in error handling ;).

提交回复
热议问题