Summary
Can you explain the reasoning behind the syntax for encapsulated anonymous functions in JavaScript? Why does this work: (function(){})();
but this doesn’t: function(){}();
?
What I know
In JavaScript, one creates a named function like this:
function twoPlusTwo(){
alert(2 + 2);
}
twoPlusTwo();
You can also create an anonymous function and assign it to a variable:
var twoPlusTwo = function(){
alert(2 + 2);
};
twoPlusTwo();
You can encapsulate a block of code by creating an anonymous function, then wrapping it in brackets and executing it immediately:
(function(){
alert(2 + 2);
})();
This is useful when creating modularised scripts, to avoid cluttering up the current scope, or global scope, with potentially conflicting variables – as in the case of Greasemonkey scripts, jQuery plugins, etc.
Now, I understand why this works. The brackets enclose the contents and expose only the outcome (I’m sure there’s a better way to describe that), such as with (2 + 2) === 4
.
What I don’t understand
But I don’t understand why this does not work equally as well:
function(){
alert(2 + 2);
}();
Can you explain that to me?