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?
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With