5

How come

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

produces SyntaxError: Unexpected token (

while

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

alerts "test123"

?

Alon
  • 3,504
  • 10
  • 42
  • 63

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,064
  • 2
  • 35
  • 53