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() {...}))())));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With