I've seen 2 versions of self executing javascript functions:
(function() { ... })()
and
(function() { ... }())
note the different placement of the function execution "()"
Is there a difference between these two?
I've seen 2 versions of self executing javascript functions:
(function() { ... })()
and
(function() { ... }())
note the different placement of the function execution "()"
Is there a difference between these two?
There are many ways to get the effect of what you're doing, and strictly speaking this topic has only tangential relation to the subject of closures.
The problem is this: in JavaScript, the function
keyword serves two different purposes:
var
statement (variable declaration) but for a function;Now the problem is that when the parser sees function
at the beginning of a statement, it assumes you mean to declare a function; that is, case 1 above. When you declare a function, you cannot call it in the same statement; the function declaration statement just declares the function.
Thus, if what you want is a statement that consists only of the creation of a function and its immediate invocation, you have to put the parser in the mood to parse an expression. Putting the whole thing in parentheses is just one way of doing that.
Any "trick" that convinces the parser that what it's seeing is an expression statement will do:
var dummy = function() { ... whatever ... } ();
!function() { ... whatever ... } ();
0 + function() { ... whatever ... } ();
All of those, and countless other examples, set things up such that when the parser sees the function
keyword, it does so in the middle of an expression.
If Mr. Eich had picked a different keyword for the instantiation of a function object mid-expression (like lambda for example), there'd be no problem, because you could then just say
lambda () { ... whatever ... } ();
He didn't, however.
The parenthesis ensure you have an expression (which cannot starts by the function
keyword), so that it may be executed.
From ECMAscript Language Specification :
Also, an ExpressionStatement cannot start with the function keyword because that might make it ambiguous with a FunctionDeclaration.
This works too :
(((((function() {...}))())));
The correct term for either of these is an immediately executing function.
Although both of these work in the same way, Douglas Crockford recommends the latter for reasons of readability.
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.
So if you want to follow that advice, you should prefer to use:
(function() { ... }())
Former is better because it treats Function as a `first-class citizen'. It use parenthesis to wrap the function and invoke it.
Em..as to latter, it also avoid syntax ambiguous.
But I recommend the former.