Friday, September 10, 2010

TO VAR OR NOT TO VAR

If you ever do anything in JavaScript, I am sure you have created functions like this:  


var myFunk = function () { 
 return 'hello, i need a hug.'; 
};
myFunk();  // hug me!


function yourFunk () { 
 return 'get away from me';
}
yourFunk(); // no love from you


And then you said to yourself: "hmmm... AWESOME!"
However, let say if there is a really magical coding earthquake that somehow magically, of course, switches your code around like this... 


yourFunk(); // away you go even before you ask
function yourFunk () {  
 return 'get away from me.';
}


myFunk(); // i need a hu... wait... ERROR!!!!
var myFunk = function () { 
 return 'hello, i need a hug.'; 
}; 

And all of sudden your online "Which-Sailor-Moon-Character-Are-You Personality Testing" site breaks when executing myFunk() while yourFunk() executes correctly! WTF!?
Children, gather around as I am about to break it down. The reason is at the JavaScript parse time, the browser will learn about the definition of yourFunk function and knows what to do. However, the anonymous function to var myFunk assignment will not happen until the run-time; and since myFunk is called before the anonymous function assignment happens, the browser will have no idea what myFunk is and it will throw an exception and start to sob uncontrollably! Isn't JavaScript wacky and interesting and mildly amusing!?

Think about it for a second, it will all make sense in a minute or two... ... ... ahhh... now I see what the VAR is going on. 

function whatsMyAlias(user) {
   if (user.Name === 'badallen'){
      return "Tuxedo Mask";
   }
  else {
     return "sorry you are not cool enough to have an alias.";
   }
}

No comments:

Post a Comment