1

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?

1
  • On FireFox: "SyntaxError: function statement requires a name." Commented Nov 2, 2011 at 9:43

2 Answers 2

9

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}

Sign up to request clarification or add additional context in comments.

5 Comments

Made quick test case, easier to demonstrate in there: jsfiddle.net/xMZbc :)
@Felix Kling robertnyman.com/2008/10/09/… the code there says link.onclick = function (num) { return function () { alert(num); }; }(i); ... so why is it working there ?
@RoyiNamir: You mean the inner or the outer function? The outer because it is an assignment expression, and the inner because of return.
@RoyiNamir: Actually that was what I'm trying to tell you. If you have an assignment, the right hand side is always interpreted as expression, hence you don't need parenthesis....
0

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

1 Comment

This is not correct. Parenthesis have a different meanings, depending on their position and context. Put after a function reference, they execute that function, but in any other case they act as grouping operation. Take var foo = (5 + 3) * 2;. There is no function execution involved here.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.