2010-01-27

JS local functions: anonymous vs. named

I could not see clearly any reasons to keep anonymous code but the disadvantages are obvious.
If you could put some arguments, please comment.









Use of anonymous functions.
Sample:
{// scope begins
    … // logic mixed with declarations
    var
_ajaxify = function(cont) {
            return ;
      };
    …
   _ajaxify(XXX);
}// scope ends

It creates anonymous function. As result you:
·         cannot see in debugger what really has been in call stack.
·         It clutters the actual code logic with mixed-in local function declarations
·         Create dependency of where the variable been initialized (if at all)


Solution: use named functions instead:

{// scope begins
   
_ajaxify(XXX);
    //logic implementation
    …
    return;
    // local functions declarations 
    function
_ajaxify( cont ) {
            return ;
    }
   
function … 

}// scope ends


·         There is no performance gain from delayed function load in var locFunc=function(){…}. See the performance tests:  500 | 1000 | 3000 | 10000 (compare Var versus Fun, like 0/2 or 4/6). Beware the last two: they are JS stress tests! 
Smaller JS footprint function locFunc(){…} – is 5 character shorter. Could be significant for large number of small functions.

Regards,
Sasha

Related blog on subject: