Is there a difference between (function() {…}()); and (function() {…})();? [duplicate]

Possible Duplicate:
Location of parenthesis for auto-executing anonymous JavaScript functions?

Sometimes I see:

(function() { ... }()); 

and sometimes I see:

(function() { ... })(); 

I see both forms with and without arguments. They both execute the anonymous function.

Is there a difference between the two forms? Are there any compelling reasons to use one form over the other?

There is no practical difference in those two forms, but from a grammatical point of view the difference between the two is that The Grouping Operator – the parentheses – will hold in the first example a CallExpression, that includes the FunctionExpression:

               CallExpression
                |         |
       FunctionExpression |
                |         |
                V         V
    (function() {       }());
    ^                      ^
    |--PrimaryExpression --|

In the second example, we have first a whole CallExpression, that holds the FunctionExpression:

          PrimaryExpression
                |
         FunctionExpression
                |
                V
    (function() {       })();
    ^                      ^
    |--  CallExpression  --|

There is no difference between the two, so far as the compiler is concerned. However, will find that the (function () {}()) style is recommended in Douglas Crockford’s JavaScript code conventions.

As far as differences go, it is really just syntactic sugar. Somewhat equivalent to: “do you like jQuery() or $()?” Both can be compiled, executed, and used interchangeably (AFAIK).

From the code samples I have seen thus far, more people seem to follow the Crockford code convention:

(function() { ... }()); 

Personally, I prefer the (function(){})(); convention because it is more apparent to me that the function is self-executing; I’m also a big user of jQuery and that’s the convention used in jQuery source.

Read More:   When do I need to specify the JavaScript protocol?

Additionally, it is considered good practice to use parens to enclose your self-executing function, regardless of which form you choose to go with.


The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Similar Posts