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?
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?
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: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 ;).Technically, the proper solution is (I believe):
You can sometimes get lazy and use
but that allows both an undefined variable x, and a variable x containing null, to return true.
Another potential "solution" is to use the
window
object. It avoids the reference error problem when in a browser.We can check
undefined
as followsThe only way to truly test if a variable is
undefined
is to do the following. Remember, undefined is an object in JavaScript.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).
You can also use the ternary conditional-operator: