0

Why does a function declaration need to be wrapped in parentheses to be immediately invoked? I'm curious as to how the interpreter reads the immediately invoked function when wrapped in parentheses.

I.e.

Why must I do this...

(function() { 
   // Logic 
 })();

and not this...

function() { 
   // Logic 
 }();
contactmatt
  • 18,116
  • 40
  • 128
  • 186
  • 1
    The second is OK where an expression is allowed, e.g. `var x = function(){return 'foo'}();` – RobG Feb 18 '13 at 03:36

1 Answers1

6

When a function is wrapped in parenthesis it's parsed as an expression - a function expression. Otherwise without them it's parsed as a function declaration. A function declaration requires a name which it sees you have not given it, which in turn causes a syntax error. Moreover, you can't apply () inline to a function declaration in order to call it. The empty parenthesis is a syntax error, but a non-empty parenthesis is an expression which will be evaluated separately from the function.

David G
  • 94,763
  • 41
  • 167
  • 253