Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why function name will not be available after assignment to a variable [duplicate]

Tags:

javascript

I just encountered this question in one of my interviews. I did not get any answer so putting it on StackOverflow

One simple question in JS but I am not able to get the reason behind it. 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 perfectly fine.

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

Why this is happening? why function can not be called with functions name after assigning the function to js variable?

like image 826
Parashuram Avatar asked Sep 29 '15 11:09

Parashuram


2 Answers

There are two ways to declare functions.

Function declaration:

function f(a,b) { }

Function expression:

var f = function(a,b) { }

In function expressions, you can also specify an "internal" function name like this:

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

The name foo will only be visible from inside the function. This is normally used in recursive functions to ensure a correct self-reference.

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

like image 80
Dmytro Shevchenko Avatar answered Oct 18 '22 13:10

Dmytro Shevchenko


For a named function expression (which is what you have) the name foo is only available within the expression itself.

MDN: If you want to refer to 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).

like image 38
Alex K. Avatar answered Oct 18 '22 13:10

Alex K.