Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading