What is the purpose of defining the name of a function that is assigned to a variable? [duplicate]

1

I was taking a look at some posts here on the site and I came across this question here . Well, in the accepted answer was explained the statement of expressions , anonymous, named and self-invoked . Causing my doubt in the named function. What is the name of the function for if the value of return is in the name of the variable and not in the name of the function. What is the purpose of naming a function that is inside a variable?

//expressão anônima de função
var a = function() {
  return 3;
}

//expressão nominada de função
var a = function bar() {            // dúvida para que serve bar
  return 3;
}

//expressão "autoinvocada" de função
(function digaOi() {
   alert("Oi!");
})();
    
asked by anonymous 13.07.2018 / 16:27

2 answers

0

It would be a matter of scope, where the function bar() is only accessible within a .

The function a gets another name bar which is only visible within a :

var a = function bar() {
  // bar é visível aqui
  return 3;
}
// bar NÃO é visível aqui
a();   //  retorna 3
bar(); // erro: bar is not defined

I do not see much use in creating a second name for the same function and the latter with a limited scope.

See in this example that both call a and bar the effect is the same:

var x = 0;
var a = function bar(){
   console.log(x);
   // setTimeout(a, 2000);
   // ou
   setTimeout(bar, 2000);
   x++;
}

a();
    
13.07.2018 / 16:56
2

As commented on the question you mentioned - and on @dvd's response, there is the difference between the scopes. When you do:

var a = function bar() {
    // ...
}

Within the function there will be a reference to the bar function itself, something that in the anonymous function will not exist.

var a = function () {

}

How could it be possible to reference something without a name? But why not by the object itself a ? Well, the function is the very definition of a , which implies that within it the a object is not defined.

And why setting the name is useful? Well, the simplest solution that could use this technique is to define a recursive function as callback of an event:

function myEvent(callback, n) {
  return callback(n);
}

const result = myEvent(function fatorial(n) {
  return (n == 0) ? 1 : n * fatorial(n-1)
}, 5);

console.log(result)
  

Note: Note that when doing

     

 
 var a = function bar() {}
 
console.log(a.name)
 
     

The value of a.name will be bar , not a .

    
13.07.2018 / 17:22