(function() {})() declaring/initializing javascript function

function, initialization, javascript

Solution

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.

Problem

Possible Duplicate: JavaScript: Why the anonymous function wrapper? I would like to ask you what is the reason of wrapping everything in ``` (function() { document.write("Hello World!"); })(); ``` function?

Original source