Search code examples
javascriptnode.jsclosuresanonymous-functionfunction-expression

Differences Between Named and Unnamed Anonymous Javascript Functions


Normally, in Javascript, when I want to pass an anonymous/inline function as an argument to another function, I do one of the following.

someFunctionCall(function() {
    //...
});

someFunctionCall( () => {
    //...
});

However, I've recently inherited a codebase that uses named function as inline arguments, like this

someFunctionCall(function foo() {
    //...
});

I've never seen this syntax before. The function still seems to be anonymous -- there's no foo function defined in either the calling or called scope. Is this just a matter of style, or can using a named function (foo above) as an anonymous function change the behavior or state of that program?

This is specifically for a NodeJS (not a browser based program) program, and I'm specifically interested in behavior specific to using functions as parameters. That said information from behavior across platforms and runtimes is welcome.


Solution

  • There are at least three advantages of using named function expressions instead of anonymous function expressions.

    • Makes debugging easier as the function name shows up in call hierarchy.
    • The function name is accessible in the inner scope of the function, so it can be used for recursion
    • The function name itself acts like a self documentation of what the function is doing instead of reading the code.