I have the code :
function (i)
{
alert(i);
}(3);
I don't understand why I don't see the alert.
What does this syntax mean?
And why this code:
( function (i)
{
alert(i);
}(3))();
Does work?
What is the difference?
What Am I Missing?
I have the code :
function (i)
{
alert(i);
}(3);
I don't understand why I don't see the alert.
What does this syntax mean?
And why this code:
( function (i)
{
alert(i);
}(3))();
Does work?
What is the difference?
What Am I Missing?
Share Improve this question edited Dec 26, 2024 at 9:47 dumbass 27.3k4 gold badges38 silver badges74 bronze badges asked Nov 2, 2011 at 9:38 Royi NamirRoyi Namir 149k144 gold badges493 silver badges831 bronze badges 1- On FireFox: "SyntaxError: function statement requires a name." – Thilo Commented Nov 2, 2011 at 9:43
2 Answers
Reset to default 9The first snippet will be interpreted as function declaration, which needs a name and your function does not have one. So this will result in an error.
Surrounding the function definition with parenthesis makes the function to be interpreted as function expression which doesn't need a name, so it is valid JavaScript.
Though it seems you are making two invocations there. It should either be
(function(i){ alert(i); }(3));
or
(function(i){ alert(i); })(3);
Typically you can have function expression either in parenthesis (everything is evaluated as expression there) or at the right side of an assignment expression (var a = function...
).
See Section 13 of the ECMAScript 5 specification:
FunctionDeclaration :
function Identifier ( FormalParameterListopt ) {FunctionBody}FunctionExpression :
function Identifieropt (FormalParameterListopt ) {FunctionBody}
The ()
-operator is responsible for executing a function, therefore a function expression which is wrapped by ()
is exectued immediately.