5
var f=function foo()
{
console.log("hello");
};

f();
foo();

This produces an error as : "Exception: ReferenceError: foo is not defined"

But "foo" is defined. Why does this happen?I know that this is a function expression and "f()" is used to access this function. But this is not an anonymous function , I do have a name for this function. Why am I not able to access the function using its name?

  • 2
    See the [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/function#Named_function_expression) In case of function expression, if you name the function, then the name is only available in the function body and not outside. – abhishekkannojia Mar 24 '17 at 06:57
  • 1
    In js all functions are variables. But in your case foo() is assigned to f. foo() will get a reference error since it is not defined. – Jijo Cleetus Mar 24 '17 at 06:58
  • foo is not defined. f is defined. – Sagar V Mar 24 '17 at 06:59
  • 1
    This syntax is called a named function expression. That name is not it's original name, it's a local variable (local to the function) that refers to the function itself so that you can write recursive anonymous functions. The function **does not have a name** - it's anonymous. Some older browsers leaked the variable into global scope so behaving like what you expected but this is considered a bug. These days all browsers I know of have fixed the bug thus the name is no longer accessible outside the function – slebetman Mar 24 '17 at 07:10
  • Thanks a lot guys. Big help. – Mukul Choudhary Apr 05 '17 at 07:18

2 Answers2

6

MDN - function expression

syntax

var myFunction = function [name]([param1[, param2[, ..., paramN]]]) {
   statements
};

The function name. Can be omitted, in which case the function is anonymous. The name is only local to the function body.

Ahmed Eid
  • 4,414
  • 3
  • 28
  • 34
2

You are conflating function expressions with function declarations.

This declares a variable foo and assigns an anonymous function to it:

var foo = function() {};

This declares a function bar in the current scope:

function bar() {};

This declares a variable baz and assigns it a function whose name is qux:

var baz = function qux() {};

Note that in this case, the function is not being declared in this scope. Only the variable is being declared. It just so happens that the name property of this function will be set to qux.

See this question.

Edit: code blocks Edit: added relevant link

Community
  • 1
  • 1
Nathan
  • 505
  • 2
  • 8