JavaScript function naming

I ask this because I just saw it in a piece of code:

var myVar = function func(arg){
   console.log(arg);
}

      

I don't understand why the function was "renamed" func

before it was defined for myVar

.

Can someone explain the interest in this, not just:

var myVar = function(arg){
   console.log(arg);
}

      

Many thanks!

+3


source to share


1 answer


In the first example, you have a variable named myVar that has a reference to a function named func. Your function has not been renamed.

In the above example, however, you have the same variable myVar, but in this case it points to an anonymous function.



The reason for choosing number one over number two is that you get a better result when errors occur, since it prints the function name. In the second example, it will simply say undefined if something goes wrong.

Edit: Found a more detailed answer here: Why use named function expressions?

+1


source







All Articles