6

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?

Tushar
  • 85,780
  • 21
  • 159
  • 179
Parashuram
  • 1,498
  • 2
  • 16
  • 36

2 Answers2

7

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.

Community
  • 1
  • 1
Dmytro Shevchenko
  • 33,431
  • 6
  • 51
  • 67
3

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

Alex K.
  • 171,639
  • 30
  • 264
  • 288