10

For one of them the "()" is inside, for the other one it is outside. Here they are:

var a = (function() {
    return {
        bla: function() {
            console.log('a');
        }
    };
} () );

var b = (function() {
    return {
        bla: function() {
            console.log('b');
        }
    };
}) ();

a.bla();
b.bla();
Zeta
  • 103,620
  • 13
  • 194
  • 236
SBel
  • 3,315
  • 6
  • 29
  • 47
  • the second one is commonly known as module pattern, am not a JS ninja and would love to see correct answer. – Kumar Mar 16 '12 at 08:36
  • possible duplicate of [Location of parenthesis for auto-executing anonymous JavaScript functions?](http://stackoverflow.com/questions/3384504/location-of-parenthesis-for-auto-executing-anonymous-javascript-functions) – Bergi Oct 15 '13 at 21:02

5 Answers5

9

There is no difference.

The [unnecessary] parenthesis are just in different places. The function declaration is already an expression due to where it is located. The parenthesis would make a difference, while still resulting in equivalent code, if the declaration was in a statement context (and ironically they would turn it back into an expression context), which it is not.


The common use of parenthesis in a similar scenario is for self-invoking functions. The parenthesis are required in this case because

function x () { alert("hi!") } ()

is parsed as

function x () { alert("hi!") }; ()

when it appears as a statement -- or "top level element of a block" -- where it is parsed as a "FunctionDeclaration". Thus the following form is often used:

(function () { alert("hi!") })()

This works because function ... is no longer a statement, as above, but an expression (parsed as a "FunctionExpression"), and the expression can continue so the Automatic Semicolon Insertion does not occur as in the previous case. Also note that the function name can be omitted.

However, because in the post the function ... appears in an on the right of an = (in an "AssignmentExpression") it is therefore already in an expression context (is parsed as a "FunctionExpression") and thus no additional parenthesis are needed.

All of these are identical, but I prefer the 2nd form (for consistency within my code):

a = function () {} ()
b = (function () {}) ()
c = (function () {} ())

Happy coding.

  • Would you care to shed some light on what is "statement context"? – Kumar Mar 16 '12 at 10:32
  • 1
    @Kumar See [section 12 of the ECMAScript 5th edition](http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf) for the grammar rules. I have added the "proper" terminology for the *two different* grammar constructs for creating function-objects. Note than an ExpressionStatement *cannot* begin with a `{` or `function` which forces a function definition which occurs as a "top level element" of a block to be treated as a FunctionDeclaration. –  Mar 16 '12 at 10:53
2

There is no real difference. Both work in the same way. If you want to pass JSLint, you will need to use the first pattern, where the invocation parentheses are inside the other set of parentheses. If you don't, you will get the following error:

Move the invocation into the parens that contain the function.

Also note that the first set of parentheses are not required. It will work without them, but again will fail JSLint:

Wrap an immediate function invocation in parentheses to assist the reader in understanding that the expression is the result of a function, and not the function itself.


A couple of related questions:

JSLint error: "Move the invocation into the parens that contain the function"

Solution for JSLint errors

Community
  • 1
  • 1
James Allardice
  • 164,175
  • 21
  • 332
  • 312
  • Have you found any reason *why* this choise was made in JSLint? It seems arbitrary... – Guffa Mar 16 '12 at 08:53
  • 1
    @Guffa - I think it was arbitrary. Just what Crockford decided he liked. Personally, I tend to follow these 2 JSLint rules, but I'm pretty sure it makes absolutely no difference (in this case at least). – James Allardice Mar 16 '12 at 08:56
  • 1
    I believe that the outer parentheses are there for readability reasons. they clearly show that the closing `()` are not a typo for any future editing by an other developer that isn't all that familiar with JS' more complex features. IMHO, same applies for shorthand if's `x == 1 ? 'foo' : y == 2 ? 'foobar' : 'bar'` takes a lot longer to read and is more error prone than `(x == 1 ? 'foo' : (y == 2 ? 'foobar' : 'bar'))`. Easier to edit later on aswell... – Elias Van Ootegem Mar 16 '12 at 09:08
  • 1
    I don't like (or use) JSLint, but +1 for pointing out this ... quirk. –  Mar 16 '12 at 11:12
1

There is no practical difference, it's just a subtle difference in how you make the Javascript engine think of the function as a value.

Using ( function(){} () ); you are causing the function to be a value because a statement can't start with a parenthesis. Using ( function(){} ) (); you are using the parentheses to first evaluate the function as a value, then call it.

Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • In both cases `function(){}` is evaluated to a function-object first. The parenthesis would force it to be an expression ... but it already is so. –  Mar 16 '12 at 11:09
  • @pst: Yes, in this case it's already an expression, but the common use of parentheses in this way is to make it an expression. That's the reason that the parentheses are there, even if they are not needed when used in an assignment. – Guffa Mar 16 '12 at 11:18
  • Fair enough; I indeed prefer the [inside] parenthesis form for consistency. –  Mar 16 '12 at 19:10
0

I think is the same difference of this:

var myObj = {bla:'blabla'}; 
var a = (myObj);
var b = myObj;

...no difference :)

Luca Rainone
  • 16,138
  • 2
  • 38
  • 52
0

the ending brackets mean that : When a function is to be invoked immediately, the entire invocation expression should be wrapped in parens so that it is clear that the value being produced is the result of the function and not the function itself. (taken from here)

So, if you use {}(), the function is immediately executed and the variable is assigned with the function result.

Then if you use ({})(), if there's a function between (), it is executed and the value is assigned to the variable.

They are the same thing if they contain the same functions in my opinion.

Taha Paksu
  • 15,371
  • 2
  • 44
  • 78