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?

3
  • 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? Commented Apr 18, 2016 at 22:15
  • 1
    Must read: stackoverflow.com/a/338053/652669 Commented Apr 18, 2016 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. Commented Apr 19, 2016 at 14:38

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.