3

I know most of people using the following script like

(function(){})();

for anonymous function call. But what's the function of the surrounding parantheses?

var g = (); // syntax error, why?
var g= (function(){}); // correct

Can anybody explain it for me?

Arjan Einbu
  • 13,543
  • 2
  • 56
  • 59
brian_wang
  • 401
  • 4
  • 16

4 Answers4

5

() is used to group an expression. When there is no expression inside, its a syntax error.

To illustrate it, see the following example.

var x = 5; // works
var y = (5); // works
var z = (); // syntax error!
Shiplu Mokaddim
  • 56,364
  • 17
  • 141
  • 187
1

The parentheses around the function expression is to make it an expression.

The syntax of a named function is too similar for a function expression to work without the parentheses in that case:

function(){}();
        ^
        |______ syntax error, function name expected

In other cases where a function expression is used, it's already known that it has to be an expression, for example:

var f = function(){};
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
1

() is used for several things within JavaScript.

Method invocation

When used as an operator, it'll be used to call a function, optionally with a list of parameters:

var a = function() { console.log(23); }
a() // => 23

You can see this, when people use anonymous functions which are called directly to create closures. just as in your example:

(function(){})();

Although i guess most people would write it this way:

(function(){}());

to indicate, that the function is grouped and the expression is part of a whole. This leads to another use case:

Grouping an expression

() can be used to group expressions. Like this:

(1,2,3);

The empty () would be a syntax error. But this would work:

a = (1,2,3);
console.log(a); // => 3

It's the case in your example:

var g = (function(){});

g has been assigned an anonymous function as it's value. This would also work:

var g = function() {};

Same effect.

Grouping has no immediate value, but when you consider creating anonymous functions for closures, it is pretty essential:

function() {
    // your code
}(); // => Syntax Error

But this will work:

(function() {
    return 12;
}());

as the expression is grouped.

Florian
  • 3,366
  • 1
  • 29
  • 35
0
  1. (function(){})();. This is a Immediately-Invoked Function Expression (IIFE). This is a very popular pattern used to avoid collisions. See this article.

  2. var g= (function(){}). This is an effective varible assignment. In fact, after executing this statement, the g variables contains the function. Let's try this:

      var g = (function(){console.log('hello')});
      g();
    
  3. var g = ();. This is not a valid syntax for the language specification. See the ECMAScript Language Specification for further details.

Alberto De Caro
  • 5,147
  • 9
  • 47
  • 73