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 04:43

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 ;).

查看更多
何处买醉
3楼-- · 2019-01-01 04:44

Technically, the proper solution is (I believe):

typeof x === "undefined"

You can sometimes get lazy and use

x == null

but that allows both an undefined variable x, and a variable x containing null, to return true.

查看更多
永恒的永恒
4楼-- · 2019-01-01 04:45

Another potential "solution" is to use the window object. It avoids the reference error problem when in a browser.

if (window.x) {
    alert('x exists and is truthy');
} else {
    alert('x does not exist, or exists and is falsy');
}
查看更多
人气声优
5楼-- · 2019-01-01 04:45

We can check undefined as follows

var x; 

if (x === undefined) {
    alert("x is undefined");
} else {
     alert("x is defined");
}
查看更多
余生无你
6楼-- · 2019-01-01 04:46

The only way to truly test if a variable is undefined is to do the following. Remember, undefined is an object in JavaScript.

if (typeof someVar === 'undefined') {
  // Your variable is undefined
}

Some of the other solutions in this thread will lead you to believe a variable is undefined even though it has been defined (with a value of NULL or 0, for instance).

查看更多
皆成旧梦
7楼-- · 2019-01-01 04:47

You can also use the ternary conditional-operator:

var a = "hallo world";
var a = !a ? document.write("i dont know 'a'") : document.write("a = " + a);

//var a = "hallo world";
var a = !a ? document.write("i dont know 'a'") : document.write("a = " + a);

查看更多
登录 后发表回答