(
function foo(){ alert("Hello world!");}
)
In the line above, we define a function foo which is interpreted as a function-object.
(
function foo(){ alert("Hello world!");}
)();
We are now calling the function (using the function-object).
NOTE: The way you have used the paranthesis is actually wrong. The above is the correct way of using them.
UPDATE:
This is actually a good question. I fiddle around it for sometime and came with the following conclusion. (Note, I might be a LOT wrong, please tell me if so.)
Its about the way JS-engine parses the code. When it parses function foo(){ alert("Hello world!");}
, it looks at it as a function declaration. It is (probably) not a statement that calls the function (may be according to the grammar of the language).
However, the following codes work
<script type=text/javascript>
[function foo(){ alert("Hello world!");}()]
</script>
and this one too:
<script type=text/javascript>
1,function foo(){ alert("Hello world!");}()
</script>
(and obviously the one in the question above)
I would assume this is because the JS parser expects an expression inside (..)
ie when it first sees a (
. This also happens with the comma-operator
as in the second code above, and when initializing the array (in the first code). But when there are no tokens that make the code (the function) look like an expression, the parses throws an error when it encounters the last ()
.
UPDATE 2 (Many thanks to Felix Kling for this):
Please refer to the detailed explanation concerning section of the grammar in CMS's response. That answer very clearly explains what I was speaking of above ie how the JS Parses differentiates between a function-declaration and a function-expression
(
function foo(){ alert("Hello world!")}()
)
is a function-expression. Thus it executes without any error.
But in
function foo(){ alert("Hello world!")}<<STOP>>()
the content till <<STOP>>
is parsed as a function-declaration and not as a function-expression. Hence when it encounters the first (
after <<STOP>>
it flags an error.