How to check a not-defined variable in JavaScript

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

    I often use the simplest way:

    var variable;
    if (variable === undefined){
        console.log('Variable is undefined');
    } else {
        console.log('Variable is defined');
    }
    

    EDIT:

    Without initializing the variable, exception will be thrown "Uncaught ReferenceError: variable is not defined..."

提交回复
热议问题