Entry
How can I check whether a variable is defined?
How can I check whether a variable is undefined?
Mar 7th, 2000 01:19
Martin Honnen,
You can check whether a variable is undefined with
if (typeof variableName == 'undefined')
Note that there are a couple of situations causing that condition to be
true:
1) You have NOT declared
var variableName;
before. In that case the above check is the only safe check as
if (!variableName)
would throw an error.
2) You have declared
var variableName;
before but not assigned it any value. In that case
if (!variableName)
is another valid check for the variable having a undefined value.
That means the above check doesn't allow you to distinguish whether a
variable has been declared or not. Only JavaScript 1.5 with the
in
operator will allow that as there you can check
if ("variableName" in window)
as for example in
var x;
alert("x" in window); // shows true
alert("y" in window); // shows false