Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't it possible to access a javascript function by its original name once it is assigned to a different var?

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?

like image 919
Mukul Choudhary Avatar asked Mar 24 '17 06:03

Mukul Choudhary


People also ask

Can function name and variable name be same in JavaScript?

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).

Can a function be assigned to a variable in JavaScript?

It is possible to use a function expression and assign it to a regular variable, e.g. const factorial = function(n) {...} .

What is the difference between VAR and function in JavaScript?

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(){} .

Do all JavaScript functions have to be named?

Functions stored in variables do not need function names. They are always invoked (called) using the variable name.


Video Answer


2 Answers

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.

like image 68
Ahmed Eid Avatar answered Nov 14 '22 23:11

Ahmed Eid


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

like image 36
Nathan Avatar answered Nov 14 '22 23:11

Nathan