NetBen Ramblings about JavaScript and frontend development.

16Jan/10Off

If/else + functions = madness

My code style might not be perfect, but the following code should be pretty straight forward in what to expect right?

if(true) {
   function test() {
      alert("SUCCESS!");
   }
} else {
   function test() {
      alert("FAIL!");
   }
}
test();
// alerts "SUCCESS!" in FireFox (3.5.7)
// alerts "FAIL!" in IE8, Opera 9.62, (win) Safari 4.0.4
// need to install and test this in google's Chrome still!

Whats going on here???!

I first encountered this "feature" in Safari and thought it was a local incident, though to my suprise, I reproduced it in other browsers as well!

Function literals float to the top of the scopeblock, however functions inside a failed clause, should be ignored by the interperter.
Am I missing the reason why so many browser vendors implemented it this way?
Is FireFox/Mozilla actually the odd duck here? And if so, for the love of god, why?
Is this a recent development? A discrepancy introduced by engines competing eachother over speed?

Also kinda weird that after years of JavaScript, I encounter this now...
Or is this something I never encountered before untill I started bloating my code for better readability, structuring and reducing if/else expressions?

Sure, we can mitigate this easily by changing our coding style and never declare functions through the literal notation, assigning anonymous functions to variables.

if(true) {
   var test = function() {
      alert("SUCCESS!");
   }
} else {
   var test = function() {
      alert("FAIL!");
   }
}
test();
// alerts "SUCCESS!" everywhere =/

But that's just plain daft... using function literals is pretty straightforward and everyone will trip constantly over this discrepancy when trying to write clean/clear code.
Now I have to explain to Java developers learning JS that they should avoid using function literal declarations...

Will investigate further.

Filed under: JavaScript Comments Off
Comments (0) Trackbacks (0)

Sorry, the comment form is closed at this time.

Trackbacks are disabled.