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