3

Please see this fiddle. For me, it's just a self-executing empty function:

function(){}()

Google Chrome 16.0.912.4 dev-m returns the error:

Uncaught SyntaxError: Unexpected token (

Why? This is especially strange because adding extraneous brackets will remove the error:

(function(){})()
Randomblue
  • 98,379
  • 133
  • 328
  • 526
  • it seems like the browser expects a name after `function` using this notation – Fender Oct 22 '11 at 16:23
  • 1
    Related: http://stackoverflow.com/questions/423228/difference-between-function-and-function – Digital Plane Oct 22 '11 at 16:25
  • Firefox gives the same error. That's because `function(){}` is the actual function you want to execute. So you have to add brackets around it to indicate that you mean the whole function! – ComFreek Oct 22 '11 at 16:25
  • Also interesting is that `x=function () {} ()` does not throw an error. – kojiro Oct 22 '11 at 16:29
  • @kojiro Maybe the browser interprets it as `(x=function () {}) ()`. – ComFreek Oct 22 '11 at 16:30
  • @kojiro: If you have an assignment, everything on right side is an expression. – Felix Kling Oct 22 '11 at 16:31
  • @ComFreek: No it does not, it is the same as `x = (function(){})();` – Felix Kling Oct 22 '11 at 16:32
  • @ComFreek Actually the assignment is enough of a clue to let the interpreter know that it's a function expression and not a function *declaration*. This is covered in the question linked above, and also more thoroughly in [What is the difference between a function expression vs declaration in Javascript?](http://stackoverflow.com/questions/1013385) – kojiro Oct 22 '11 at 16:34
  • @FelixKling You're right! Interesting link ;) By the way even IE 6 can handle such declarations! – ComFreek Oct 22 '11 at 16:34

1 Answers1

8

ExpressionStatement :

[lookahead ∉ {{, function}] Expression ;

Because a function () {}() is not a statement as defined in ES5.1

And a valid program has to be a statement.

Expression Statement.

however the following

!function () {}();

is a valid statement, so is using () and so is var ret = function () {}()

Raynos
  • 156,883
  • 55
  • 337
  • 385
  • Why is `function(){}()` not a statement. It is the statement "execute the empty function", isn't it? – Randomblue Oct 22 '11 at 16:29
  • 2
    @Randomblue: There are two ways to interpret this and the standard is to interpret it as function declaration, which requires a name. – Felix Kling Oct 22 '11 at 16:30