Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does calling a named assigned function fail in JavaScript?

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?

like image 658
Christian Avatar asked Feb 08 '23 05:02

Christian


1 Answers

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.

like image 193
Quentin Avatar answered Feb 10 '23 12:02

Quentin