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 get no errors either.
var add = function add(a,b){
return a+b;
};
What's going on in the second case?
There are two uses of the function
keyword in Javascript: function declarations and function expressions. Function declarations don't allow anything to the left of the keyword, e.g.
function add(a,b){
return a+b;
}
and they always require a name, e.g. add
. Meanwhile, your examples invoke the other type, function expressions, which don't require a name (but can be named!) and always require something to their left, e.g. your
var add = function(a,b){
return a+b;
};
or even a single parenthesis:
(function(a,b){
return a+b;
})(1,2); // 3
So now that we've got some vocabulary down, what you've got in your second example, reprinted—
var add = function add(a,b){
return a+b;
};
—is a function expression (namely, variable assignment into add
) whose function happens to be named.
Now, what's the purpose of this named function expression?
It's expressly for accessing the function within itself! According to MDN's documentation,
If you want to refer to 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).
Let's rename your add
s so we can talk about things less confusingly:
var abc = function xyz(a,b){
return a+b;
};
In the above, abc
will be accessible in the outer scope, while xyz
will not be. Meanwhile, vice versa: abc
will not be accessible in the inner scope, while xyz
will be.
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