()
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.