0

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?

Shadow The GPT Wizard
  • 66,030
  • 26
  • 140
  • 208
Royi Namir
  • 144,742
  • 138
  • 468
  • 792

2 Answers2

10

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}

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • Made quick test case, easier to demonstrate in there: http://jsfiddle.net/xMZbc/ :) – Shadow The GPT Wizard Nov 02 '11 at 09:45
  • @Felix Kling http://robertnyman.com/2008/10/09/explaining-javascript-scope-and-closures/ the code there says `link.onclick = function (num) { return function () { alert(num); }; }(i);` ... so why is it working there ? – Royi Namir Nov 02 '11 at 10:03
  • @RoyiNamir: You mean the inner or the outer function? The outer because it is an assignment expression, and the inner because of `return`. – Felix Kling Nov 02 '11 at 10:53
  • @Felix http://stackoverflow.com/questions/7979184/javascript-self-executing-supposed-to-work – Royi Namir Nov 02 '11 at 10:57
  • 1
    @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.... – Felix Kling Nov 02 '11 at 12:11
0

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

Neq
  • 66
  • 3
  • 3
    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. – Felix Kling Nov 02 '11 at 16:31