Search code examples
javascriptfunctionexpressionidentifier

Are there any problems with using the same identifer for both a function expression and the var I assign the function expression to?


For example:

var foo = function foo() {};

So far I haven't encountered any problems, but I wonder why I don't see this more often after learning that named function expressions are preferred over anonymous function expressions.


Solution

  • Nope, that's absolutely fine. Note that it's nearly identical to

    function foo() {
    }
    

    The only difference (but it's a significant one!) is that my example (a function declaration) is hoisted and yours (a named function expression) is not. That also means mine can't appear within a flow-control structure (such a block connected to an if or loop) and yours can. Other than that, they do the same things:

    • Create an identifier foo in the current scope that refers to the function

    • Create a function with a name (which is also foo); that name is in-scope within the function

    Without your var foo =, a named function expression does the latter but not the former.


    On some obsolete JavaScript engines, named function expressions were handled incorrectly, but anything vaguely modern (so, not IE8) works correctly.