Gary
Gary

Reputation: 51

var NAME = function NAME (){ }; - Function Name 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 get no errors either.

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

What's going on in the second case?

Upvotes: 5

Views: 150

Answers (3)

Charlie
Charlie

Reputation: 23838

In both the cases you are ended up having a function called add().

But the following behavior is interesting against this backdrop.

var add = 1;
function add() {};

add();     //<-- Error not a function

Upvotes: 0

Andrew Cheong
Andrew Cheong

Reputation: 30283

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

Upvotes: 3

zangw
zangw

Reputation: 48486

This function

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

Could be interpreted roughly 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;
}

Upvotes: 1

Related Questions