Can you explain the reasoning behind the syntax for encapsulated anonymous functions in JavaScript? Why does this work: (function(){})(); but
Perhaps the shorter answer would be that
function() { alert( 2 + 2 ); }
is a function literal that defines an (anonymous) function. An additional ()-pair, which is interpreted as an expression, is not expected at toplevel, only literals.
(function() { alert( 2 + 2 ); })();
is in an expression statement that invokes an anonymous function.