Possible Duplicate:
Detecting an undefined object property in JavaScript
I wanted to check whether the variable is defined or not.
eg
alert( x );
Throws a not defined error
How can I catch this error?
I wanted to check whether the variable is defined or not. eg
Throws a not defined error
| |||||
feedback
|
This question covers exactly the same ground as earlier questions on this topic; its answers may be merged with another identical question. See the FAQ.
in JavaScript null is an object. There's another value for things that don't exist, undefined. The DOM returns null for almost all cases where it fails to find some structure in the document, but in JavaScript itself undefined is the value used. Second, no, they are not directly equivalent. If you really want to check for null, do:
If you want to check if a variable exist
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:
I probably forgot some method as well... | |||||||||||||||||||
feedback
|
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. | ||||
feedback
|
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). | ||||
feedback
|
| |||
feedback
|
I've often done:
| |||||||
feedback
|
Even easier and more shorthand version would be:
OR
| |||||
feedback
|