Undefined vs. “Undefined”
There is no built-in equivalent of PHP’s isset() function in Javascript. Searching the internet for ways to work around this, you’ll see a lot of people recommend testing the (possibly undeclared) against undefined. In Venkman/Firefox, there is some unusual behavior here, which I haven’t seen mentioned elsewhere.
First of all, the recommended code:
var foo = 1;
if (foo === undefined)
{alert(”No foo”);}
else
{alert(”foo”);}
This will pop-up a window that says “Foo.”
Compare this to the following:
if (bar === undefined)
{alert(”No bar”);}
else
{alert(”bar”);}
This code will generate an error (”bar is not defined”) in Firebug, and presumably in the default debugger as well. Adding a single line fixes this:
var bar;
if (bar === undefined)
{alert(”No bar”);}
else
{alert(”bar”);}
This pops up a dialog that says, simply, “No bar.”
Rather than worry about an explicit declaration of a variable, you may try some code that uses typeof() to test if a variable exists or not. But, there’s a pitfall that I ran into — the following code is not correct.
var bar;
if (typeof(bar) === undefined)
{alert(”No bar”);}
else
{alert(”bar”);}
This code will actually output “bar”! It turns out that typeof returns the string “undefined” rather than the value undefined. So, in order to perform a test that should work right “no matter what” the code’s that actaually needed is:
if (typeof(bar) === “undefined”)
{alert(”No bar”);}
else
{alert(”bar”);}
This will output “No bar” as expected, with or without a preceding “var bar;”