Var NAME = function NAME () {}; - The function name is used twice

In Javascript, one standard way to declare a function is as follows:

var add = function(a,b){ return a+b; }; 

However, when I repeat the function name on the right side of the syntax, I also get no errors.

 var add = function add(a,b){ return a+b; }; 

What happens in the second case?

+5
source share
3 answers

There are two ways to use the function keyword in Javascript: function declarations and function expressions. Function declarations do not allow anything to the left of the keyword, for example.

 function add(a,b){ return a+b; } 

and they always require a name, for example. add . Meanwhile, your examples refer to other types, function expressions that do not require a name (but can be named!) And always require something to their left, for example. your

 var add = function(a,b){ return a+b; }; 

or even one parenthesis:

 (function(a,b){ return a+b; })(1,2); // 3 

So, now that we have some vocabulary that you have in your second example, reprinted -

 var add = function add(a,b){ return a+b; }; 

is an expression of a function (namely, assigning a variable to add ), whose function is called a name.

Now, what is the purpose of this function name?

It is clearly intended to access functions within itself! According to the MDN documentation ,

If you want to access the current function inside the function body, you need to create a named function expression. This name is then local only to the function body (scope).

Rename your add so we can talk about things less vaguely:

 var abc = function xyz(a,b){ return a+b; }; 

In the above example, abc will be available in the outer scope, but xyz will not. Meanwhile, vice versa: abc will not be available in the inner area, and xyz will.

+3
source

This function

 var add = function add(a,b){ return a+b; }; 

It can be interpreted approximately as

 // the scope of outer `add` is here var add = function (a, b) { var add = ...self... // something like that. the scope of this `add` is here return a + b; } 
+1
source

In both cases, you have a function called add() .

But against this background, the following is more interesting.

 var add = 1; function add() {}; add(); //<-- Error not a function 
0
source

Source: https://habr.com/ru/post/1241105/


All Articles