If you know the variable has been declared or assigned in global scope:
if (window.x) {
is efficient,
if (x) {
simple.
If you know the variable has been declared in function scope:
if (x) {
is efficient and simple.
But those are not really very good. "if(x)" fails if x has not been declared, and they give wrong answers if x = 0;
I recommend the following as it works even if the variable has not been declared:
if (typeof(x) == 'undefined') {
The hardest case is if for some reason you need to find out if the variable has been declared or not:
var declared = true;
try {
x;
} catch (e) {
declared = false;
}
if (declared) {
And BTW, null is just a reference of type Object that does not point to an instance.
No comments:
Post a Comment