0

Why do we have ( before function word here?

(function() {

     var message = "Привет"; function showMessage() {
    alert( message );   }

     showMessage();

})();
Adam Azad
  • 10,675
  • 5
  • 25
  • 63

1 Answers1

1

Try not to:

function() { return 1; }()

then you will get Uncaught SyntaxError: Unexpected token (

JavaScript parser runs in two modes, lets call it expression mode and normal mode, in normal mode JS parser expects top level declarations like functions and code blocks. You use '(' to enter expression mode, in expression mode function() { } will be interpreted as constant whose value is a function.

There is similar case with objects literals:

{ foo: 1 }

without '(' this means block of code, where you have single expression - constant 1 proceeded by label, when you use ({ foo: 1 }) parser enters expression mode and interprets it as object literal with property foo.

Why two modes, it is enforced by language grammar which in case of JS is pretty complicated (like in most C based languages).

csharpfolk
  • 3,778
  • 20
  • 26