That doesn't have ()()
, it has (function(){})()
.
The function syntax is function(){}
and the function call operator is ()
. The parentheses that wrap the function are not technically special and you could instead replace them with !
:
!function(){}()
Doing this wouldn't work:
function(){}()
Because this in a statement context, the function
starts a function declaration rather than expression. The syntax then fails because a function declaration must have a name.
If we have !function(){}
(or (function(){}
), then it couldn't be a statement because !
(or (
) already expects an expression, so it will be treated as an expression.
So you could do this without any extra:
var a = function() {
return false;
}();
Because var a =
is already expecting an expression, function
cannot possibly be the start of a function declaration.
An easy way to litmus test whether your function will be seen as an expression or declaration is to ask yourself, could I use var x
here?
For instance:
var x; //all is fine, so if I said function here, it would be a start of a function declaration
(var x) //Gives an error, so replacing var x with a function would be a function expression
var myVar = var x; //Gives an error, so replacing var x with a function would be a function expression
And so on