28

Why I can write

 var foo = function(){}();

But can not

 function(){}();

Are there are any design reasons?

Stan Kurilin
  • 14,860
  • 20
  • 75
  • 127
  • 2
    Function declarations vs function statements, duplicates already exist. – Rob W Nov 10 '11 at 21:41
  • possible duplicate of [Explain JavaScript's encapsulated anonymous function syntax](http://stackoverflow.com/questions/1634268/explain-javascripts-encapsulated-anonymous-function-syntax) – Rob W Nov 10 '11 at 21:45

3 Answers3

39

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?

Community
  • 1
  • 1
Dave Newton
  • 152,765
  • 23
  • 240
  • 286
7

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.

kemiller2002
  • 107,653
  • 27
  • 187
  • 244
2

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

dyoo
  • 10,955
  • 1
  • 29
  • 41