Search code examples
javascriptfirst-class-functions

How does an anonymous function know its name?


Consider the following code.

const foo = () => {};
console.log(foo.name); // prints foo
const bar = foo;
console.log(bar.name); // prints foo again

Please point out what is wrong with my reasoning about the statement const foo = () => {};. The expression () => {} evaluates to an anonymous function object and the statement binds the name foo to that object. Surely the value of the expression () => {} does not know it has name foo, but somehow it knows after foo is bound to it. But how did that happen? I assume that = does not alter the right-hand side and lines 3 and 4 behave as I expected.


Solution

  • According to the specification, when a variable declaration is evaluated and the initializer is an anonymous function definition, then that definition is evaluated in a special way, passing along the name of the variable to be used as function name:

    LexicalBinding : BindingIdentifier Initializer
    1. Let bindingId be StringValue of BindingIdentifier.
    2. Let lhs be ! ResolveBinding(bindingId).
    3. If IsAnonymousFunctionDefinition(Initializer) is true, then
       a. Let value be ? NamedEvaluation of Initializer with argument bindingId.
    ...

    Something similar happens when evaluating an assignment expression.