Today, one of my major misconceptions regarding the handling of “undefined” variables in JavaScript got corrected.

I had to call a function if that function was loaded, else show an alert window as

if  (foo) {
  foo();
}  else  {
  alert("something");
}

In the scenario where foo was yet to be loaded, I got an error saying “foo is not defined”.  I was a bit taken back as until today I was under the misconception that in JavaScript if a variable is not defined (not not initialized..the pun is not intentional ;)) and I use it in a condition evaluation, it evaluates to false. This was because usually I do not do it as above. I usually check as to whether a variable is defined or not using the typeof function as below.

if  (typeof foo  != 'undefined') {
  foo();
}  else  {
  alert("something");
}

So, moral of the story. In JavaScript, I can use a variable in condition evaluation only if it has been defined (does not matter whether it has been initialized or not).

Advertisements