I just read Ben Alman's article on Immediately-Invoked Function Expressions and wondered about this part, where he's introducing function expressions and closures (not really related to IIFEs yet):
// ...doesn't it stand to reason that the function expression itself can // be invoked, just by putting () after it? function(){ /* code goes here */ }(); // This works! Well, almost. A minor JavaScript syntax issue actually // requires that ambiguity between function declarations and function // expressions be eliminated, which can be done by wrapping the function // expression in parens. // The following pattern is used universally to create an anonymous // closure with "privacy": (function(){ /* code goes here */ })(); // This parens syntax is also valid (I prefer the previous version): (function(){ /* code goes here */ }());
That last part struck me. Can anybody explain why there are two different syntactical versions for invoking function expressions?
Was this syntax consciously introduced just for invoking anonymous closures? Or is it a by-product of some other syntactical property?
Why does the second version work anyway? The first one makes sense to me from a parser standpoint. The first pair of parens evaluates to a function object, the second pair invokes this function object. But the second one? It doesn't look like it's resolving the mentioned syntactical ambiguity.
Can anybody tell me what I'm missing here?