Anonymous function vs. separate named function for initialization in jquery

coding-stylejquery

Let's say we have some code that is used to initialize things when a page is loaded and it looks like this:

function initStuff() { ...}
...
$(document).ready(initStuff);

The initStuff function is only called from the third line of the snippet. Never again. So usually people put this into an anonymous callback like this:

$(document).ready(function() { 
    //Body of initStuff
});

Having the function in a dedicated location in the code is not really helping with readability, because with the call on ready() makes it obvious that this is initialization code.

Are there any other reasons to prefer one over the other?

Best Answer

As @Stargazer712 mentioned, the first clutters the global namespace, so the second one is the winner IMHO. Now, having said that, because you're using an anonymous function in the second example, your debugger's callstack will be useless and will get differing results depending on the debugger you use. Ususally, what I end up going with is:

$(document).ready(function MODULE_init() { 
    //Body of initStuff
});

That way, the global namespace doesn't get cluttered and you have a useful callstack.

I tend to use the above convention in all anonymous (well, not anonymous anymore ;)) function definitions. It's a convention that I found when browsing through Firefox JS code.

Edit: Now having said all that, Oliver brings up a good point with unit tests. The above is meant to act as a wrapper for more complex operations, not to house a ton of untested code.