Difference between function declarations in JS

After a little (re)search, I couldn't find any mention of this, so I'm including this observation here. It concerns a difference between the two more common ways of declaring a function in JavaScript. While with function myfunc(arg){...}, it is possible to call myfunc before the declaration, when using var myfunc=function(){...}, myfunc is not available before the declaration. In other words, function names are stored during compilation, while variables (not surprisingly) get their values during execution only.

That is, this results in an error:

myfunc(0);
var myfunc=function(x){ alert(x); }

While this works fine:

myfunc(0);
function myfunc(x){ alert(x); }

For other aspects of function declarations, objects and prototypes, please see http://www.permadi.com/tutorial/jsFunc/index.html.

Popular Posts