02 December 2008

Javascript's Undeclared versus Undefined

I learned the hard way that undeclared is different than undefined. If you try to test the simple way for an undeclared variable, you get an error, which in my environment means an annoying pop-up.
/* var a; */  // undeclared
var b; // undefined

// This would cause an 'object undefined' error
/*
if (a) {
alert("a is defined");
}
else {
alert("a is undefined");
}
*/

if (typeof(a) == "undefined") {
// this will be executed
alert("a is undeclared or undefined");
}
else {
alert("a is declared and defined");
}

if (b) {
alert("b is defined");
}
else {
// this will be executed
alert("b is undefined");
}

if (typeof(b) == "undefined") {
// this will be executed
alert("b is undeclared or undefined");
}
else {
alert("b is declared and defined");
}

No comments: