(function() {})() declaring/initializing javascript function
Self executing anonymous function's main purpose is to wrap everything in a private namespace, meaning any variables declared do not pollute the global namespace, basically like a sandbox.
var test = 1;
test
would pollute the global namespace, window.test would be set.
(function() {
var test = 1; alert( test );
})();
window.test is undefined, because it's in our private sandbox.
That "protects" the global namespace from contamination.
(function() {
var something = "a thing";
// ...
if (something != "a thing") alert("help!");
// ...
function utility(a, b) {
// ...
};
// ...
})();
Now, those temporary variables and functions are all protected inside that outer throw-away function. Code inside there can use them, but the global namespace is kept clean and free of dirty, unwanted variables.
The global namespace is a precious resource. We should all be aware of its importance to ourselves and, especially, for our children.