5

How come

function(){ alert("test123");}()

produces SyntaxError: Unexpected token (

while

!function(){ alert("test123");}()

alerts "test123"

?

Alon
  • 3,734
  • 10
  • 45
  • 64

1 Answers1

3

It's because by adding ! sign you convert the declaration into an expression and invoke it immediately. By enclosing your function into brackets you will make first example working without errors:

(function(){ alert("test123");})()

To make it clearer you can think about first expression as something like:

if (false || !function(){ return false; }())


And as @zerkms noticed there is a complete explanation of Immediately-invoking functions.
Anatolii Gabuza
  • 6,184
  • 2
  • 36
  • 54
  • too bad I can't write a proper answer, but... "identifier" is not the correct term. Rather the distinction is between a definition and an expression. The former cannot be immediately invoked. – John Dvorak Aug 27 '13 at 08:18
  • 1
    Right track but wrong explanation. The ! converts the declaration into an expression. – slebetman Aug 27 '13 at 08:18
  • I can define a function and _not_ invoke it: `!function(){alert("will not be called")}` – John Dvorak Aug 27 '13 at 08:20