NetBen Ramblings about JavaScript and frontend development.

16Jan/10Off

Mea culpa, it was obvious.

Kind guys in prototype IRC channel pointed me to this article http://yura.thinkweb2.com/named-function-expressions/ which explains what's happening.
qFox from fronteers IRC also kicked me in the groins for not knowing the difference between expressions and declarations.

Basically, declarations are compiled before anything else inside a scopeblock, causing the "functions float to top" feature.

1
2
3
4
test(); // alerts "Hello world!"
function test() { // declaration
   alert("Hello world");
}

This ofcourse creates ambiguous code and should not be done if you want your code to be clear and appearant.
Instead declare functions as part of an expression by assigning them to variables or properties.

1
2
3
4
5
test(); // alerts undefined
var test = function test() { // expression
   alert("Hello world");
}
test(); // alerts "Hello world!"

The fact that it seems to work in FireFox is because they foolproofed it and now I get it, I feel they shouldn't have.
Though the declaration spec creates ambiguity, it's the spec, it does exactly as ordered and a browser should not fix developer mistakes and incompetence.
(Yeh, I was incompetent myself for not knowing this! I admit it! sigh)

I read a lot of books, written a lot of JS code and read oogles of JS articles on the web and this little piece of (in hindsight) common wealth information always eluded me. So leaving my rather newbish blog post up so other devs who run into this, will have yet another article to explain what they're encountering.

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

Sorry, the comment form is closed at this time.

Trackbacks are disabled.