gihrig (2) [Avatar] Offline

Since you guys covered advanced Javascript in detail in chapter two (that chapter is worth the cost of the book, by the way smilie, I think this one is 'fair game'.

Can you tell me if there is any material difference between a variable pointing to an anonymous function, and a named function?


var myFunc = function () {...
function myFunc() {...

It seems the first pattern is very common, not only in your book, but around the web in general. As far as I have been able to tell, the only difference is the first form obscures it's name in error messages and stack traces. How can that be such a good thing that 'everyone' does it that way?

Did I miss something?


seasoup (37) [Avatar] Offline
Re: Anonymous vs. named functions
Hi Glen, thanks so much for reading and for your compliments. While the material difference is in hoisting, the function foo(){} definition will be hoisted to the top of the block and var foo=function (){} will only have the variable hoisted as undefined and the definition will not be available until that point in he code, the real reason people define it that way by default is that it is clearer what is happening. Functions are first class objects and it is clearer what is happening to assign it to a variable. As far as I know that's why people use it.
michael.mikowski (247) [Avatar] Offline
Re: Anonymous vs. named functions
I agree with Josh's assessment. While the first example is an anonymous function assigned to a variable, this form is supported by Chrome debugging tools where assigned anonymous functions are pretty much indistinguishable from a named function. The assigned name is properly listed in stack traces and error messages.