Aadit M Shah Aadit M Shah - 2 months ago 12
Javascript Question

Are anonymous function assignment variables locally available?

I always thought that anonymous functions have no

name
but that's not the case when assigned:



const foo = () => {};

console.log(foo.name); // expected "" but got "foo"





That got me wondering whether the variable name is also local to the anonymous function:

const fact = n => n > 0 ? n * fact(n - 1) : 1;
// ^
// |
// Is fact a local variable?


If it's not local then for recursive functions like
fact
we need to travel up the scope chain. Obviously, this is not a major performance issue. Nevertheless, I'm curious to know whether the function variable name is local within the anonymous function.

Answer Source

I'm curious to know whether the function variable name is local within the anonymous function.

No. This is only the case for named function expressions (and it's not exactly a local variable even there).

We need to travel up the scope chain. Obviously, this is not a major performance issue.

It's not a performance difference at all. Scope chains are static and it doesn't really matter for performance in which scope a variable is.

I always thought that anonymous functions have no name but that's not the case when assigned.

Yes, it's a new ES6 feature that anonymous function expressions which directly get assigned to a variable will get their .name property set. However, this has nothing to do with their scope.