4

The following is probably a bit senseless, but why does the first call below work while the second one fails?

var foo = function bar() {
  console.log("Martini");
}

foo(); // works
bar(); // undefined; i.e. "Uncaught ReferenceError: bar is not defined"

Has that to do with scope?

Corollary beginner's question: The function definition "parses" - but is that actually valid syntax - and is there any context where naming an assigned anonymous function makes sense?

Christian
  • 5,291
  • 9
  • 40
  • 85
  • I think I found the answer to the second part of my question here: [In Javascript, when is it necessary to assign a named function to a variable?](http://stackoverflow.com/questions/33627048/in-javascript-when-is-it-necessary-to-assign-a-named-function-to-a-variable) – Christian Apr 18 '16 at 22:15
  • 1
    Must read: http://stackoverflow.com/a/338053/652669 – GG. Apr 18 '16 at 22:18
  • 1
    Another important difference between function declarations / expressions is, that the former are hoisted with their name and function body, while the latter are only hoisted with their name, that is, `foo` is `undefined` until its function body is reached in the code. – scriptum Apr 19 '16 at 14:38

1 Answers1

8

Function declarations create a variable with the same name as them in the current scope.

Function expressions (named or anonymous) do not. The name of a function expression is available as a variable inside the function (where it is useful for calling itself recursively) and in debugging tools.

Quentin
  • 800,325
  • 104
  • 1,079
  • 1,205