Why the function name will not be available after assigning the variable

I just came across this question in one of my interviews. I did not receive a response, putting it on StackOverflow

One simple question in JS, but I can not understand the reason for this. Below is the code.

var f = function foo(a, b) { console.log(a + "-" + b); //f(1,2) will print 1-2 //foo(1,2) is undefined. } 

Now, if I do f(1,2) , then it works fine.

But if I do foo(1,2) , then it says an undefined function .

Why is this happening? why can't a function be called with a function name after assigning the function to js?

+6
source share
2 answers

There are two ways to declare functions.

Function declaration:

 function f(a,b) { } 

Functional expression:

 var f = function(a,b) { } 

In function expressions, you can also specify the "internal" function name as follows:

 var f = function foo(a, b) { } 

The name foo will only appear inside the function. This is commonly used in recursive functions to ensure proper self-reference.

Please refer to the ECMAScript 5 specification, section 13, for more detailed differences between function declarations and expressions.

+7
source

For the function name of the function (this is what you have), the name foo available only in the expression itself.

MDN: If you want to access the current function inside the function body, you need to create a named function expression. This name is then local only to the function body (scope).

+3
source

All Articles