views:

114

answers:

3

I was recently comparing the current version of json2.js with the version I had in my project and noticed a difference in how the function expression was created and self executed.

The code used to wrap an anonymous function in parenthesis and then execute it,

(function () {
  // code here
})();

but now it wraps the auto-executed function in parenthesis.

(function () {
  // code here
}());

There is a comment by CMS in the accepted answer of Explain JavaScript’s encapsulated anonymous function syntax that "both: (function(){})(); and (function(){}()); are valid."

I was wondering what the difference is? Does the former take up memory by leaving around a global, anonymous function? Where should the parenthesis be located?

+3  A: 

They're virtually the same.

The first wraps parentheses around a function to make it a valid expression and invokes it. The result of the expression is undefined.

The second executes the function and the parentheses around the automatic invocation make it a valid expression. It also evaluates to undefined.

I don't think there's a "right" way of doing it, since the result of the expression is the same.

> function(){}()
SyntaxError: Unexpected token (
> (function(){})()
undefined
> (function(){return 'foo'})()
"foo"
> (function(){ return 'foo'}())
"foo"
meder
+3  A: 

In that case it doesn't matter. You are invoking an expression that resolves to a function in the first definition, and defining and immediately invoking a function in the second example. They're similar because the function expression in the first example is just the function definition.

There are other more obviously useful cases for invoking expressions that resolve to functions:

(function_a || function_b)()
Triptych
A: 

There isn't any difference beyond the semantics.

Regarding your concerns about the second method of doing it:

Consider:

(function namedfunc () { ... }())

namedfunc will still not be in the global scope even though you provided the name. The same goes for anonymous functions. The only way to get it in that scope would be to assign it to a variable inside the parens.

((namedfunc = function namedfunc () { ... })())

The outer parens are unnecessary:

(namedfunc = function namedfunc () { ... })()

But you didn't want that global declaration anyways, did you?

So it it boils down to:

(function namedfunc () { ... })()

And you can reduce it even further: the name is unnecessary since it will never be used (unless your function is recursive.. and even then you could use arguments.callee)

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

That's the way I think about it (may be incorrect, I haven't read the ECMAScript specification yet). Hope it helps.

CD Sanchez