How to check a not-defined variable in JavaScript

后端 未结 14 930
陌清茗
陌清茗 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 error is telling you that x doesn’t even exist! It hasn’t been declared, which is different than being assigned a value.

    var x; // declaration
    x = 2; // assignment
    

    If you declared x, you wouldn’t get an error. You would get an alert that says undefined because x exists/has been declared but hasn’t been assigned a value.

    To check if the variable has been declared, you can use typeof, any other method of checking if a variable exists will raise the same error you got initially.

    if(typeof x  !==  "undefined") {
        alert(x);
    }
    

    This is checking the type of the value stored in x. It will only return undefined when x hasn’t been declared OR if it has been declared and was not yet assigned.

提交回复
热议问题