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?
Variables and functions share the same namespace in JavaScript, so they override each other. if function name and variable name are same then JS Engine ignores the variable. With var a you create a new variable. The declaration is actually hoisted to the start of the current scope (before the function definition).
It is possible to use a function expression and assign it to a regular variable, e.g. const factorial = function(n) {...} .
A variable is something, which stores data. A function is a bunch of code, which can be executed, if you call. But a function can be a variable, too, as it stores data and values, too. See the following syntax: var functionname = function(){} .
Functions stored in variables do not need function names. They are always invoked (called) using the variable name.
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.
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
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