Skip to content Skip to sidebar Skip to footer

Why Function Statement Requires A Name?

Why I can write var foo = function(){}(); But can not function(){}(); Are there are any design reasons?

Solution 1:

The first example is an assignment: the right-hand side is an expression, and the immediate execution of an anonymous function makes sense.

The second example is a declaration: once the closing "}" is hit the declaration has ended. Parens on their own don't make sense--they must contain an expression. The trailing ")" is an error.

Standalone declarations must be turned into expressions:

(function() {})();  // Or...
(function() {}());

The first makes the declaration an expression, then executes the result. The second turns both declaration and execution into an expression.

See also When do I use parenthesis and when do I not?


Solution 2:

You can (function(){})();, and you aren't naming the function in: var foo = function(){}();

You are setting foo to the return value of the function which in your case is undefined, because all functions return something in JavaScript.


Solution 3:

The first use of function

var foo = function(){}()

is in expression position, not statement position. The second one, on the other hand, is at the top-level, and works as a function statement. That is, 'function' can be used in two different contexts, and it can mean subtly different things.

If you want to make anonymous functions without names, you do that with a function expression. And, just because of the way JavaScript language grammar works, you'll need parens in certain context, as Dave Newton mentions, because the place where you're putting the word 'function' can be confused with its statement version (which does require a name).


Post a Comment for "Why Function Statement Requires A Name?"