Skip to content Skip to sidebar Skip to footer

Self Executing Function Doesnt Work?

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)

Solution 1:

The 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}


Solution 2:

The ()-operator is responsible for executing a function, therefore a function expression which is wrapped by () is exectued immediately.


Post a Comment for "Self Executing Function Doesnt Work?"