Tuesday, November 18, 2008

Javascript undefined

I've seen lots of blogs written about how to tell if a Javascript variable has been defined, but all I've seen are incomplete. Here's are some good and bad ways.

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.