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?
() 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!
() is used for several things within JavaScript.
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:
() 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With