How to check a not-defined variable in JavaScript

2019-01-01 04:41发布

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 catch this error?

13条回答
梦寄多情
2楼-- · 2019-01-01 05:04

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.

查看更多
登录 后发表回答