Possible Duplicate:
Detecting an undefined object property in JavaScript
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
How can I catch this error? |
|||||||||||||
|
In JavaScript, Second, no, there is not a direct equivalent. If you really want to check for
If you want to check if a variable exists
If you know the variable exists, but don't know if there's any value stored in it:
If you want to know if a member exists independent of whether it has been assigned a value or not:
If you want to to know whether a variable autocasts to true:
Don't do this, because there is no constant named undefined. It will work, but only so long as someone doesn't create a variable named undefined:
I probably forgot some method as well... |
|||||||||||||||||||||
|
The only way to truly test if a variable is
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). |
|||||||||||||||||||||
|
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. |
|||||||||||||||||
|
An even easier and more shorthand version would be:
OR
|
|||||||||||||||||
|
I've often done:
|
|||||||||||||
|
You can also use the ternary conditional-operator:
|
|||||||||||||
|
We can check
|
|||
|
I often use the simplest way:
|
|||||
|
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?