8

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?

peterh
  • 1
  • 15
  • 76
  • 99
Marcin
  • 5,289
  • 15
  • 52
  • 68

2 Answers2

13

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.

meder omuraliev
  • 177,923
  • 69
  • 381
  • 426
5

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.

Pointy
  • 389,373
  • 58
  • 564
  • 602