0

Very straight-forward, so the question is why

(function(){ console.log('a'); }()); // 'a'

or

(function(){ console.log('a'); })(); // 'a'

work, but

function(){ console.log('a'); }() // SyntaxError: Unexpected token (

gives an error? What's the meaning behind this behavior? Or what's the purpose of those extra parentheses?

Silviu-Marian
  • 10,565
  • 6
  • 50
  • 72

2 Answers2

1

The extra parentheses convert the function into a function expression instead of a function declaration.

Only a function expression can be invoked immediately with the trailing ().

Alnitak
  • 334,560
  • 70
  • 407
  • 495
1

There is no clear explanation for that. JavaScript simply can't parse function(){ console.log('a'); }() successfully. This also happens with other examples, like this one:

1.toString();    // Syntax error
(1).toString();  // Works

An (working) alternative to your code would be (note the ! at the beginning):

!function(){ console.log('a'); }()
Danilo Valente
  • 11,270
  • 8
  • 53
  • 67