Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(function() {})() declaring/initializing javascript function [duplicate]

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?

like image 774
Marcin Avatar asked Mar 08 '10 13:03

Marcin


People also ask

What is the purpose of the JavaScript function initialize ()?

the initialize function is called everytime when the script is instantiated so any code within the function is executed no matter the sub-function that is called via the external script. This is useful for declaring re-usable variables, starting logging etc.

How do you initialize a function in JavaScript?

the Init Functions in JavaScript. When functions are used only once, an Immediately Invoked Function Expression (IIFE) is common. Copy (function() { /* Set of instructions */ })(); (() => { /* Set of instructions */ })(); IIFEs are function expressions called as soon as the function is declared.

Can you define a function twice in JavaScript?

functions are data in memory stack, so when you define another function with the same name, it overrides the previous one. Show activity on this post. Well obviously you're not meant to define the same function twice. However, when you do, the latter definition is the only 1 that applies.


2 Answers

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.

like image 87
meder omuraliev Avatar answered Oct 08 '22 14:10

meder omuraliev


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.

like image 41
Pointy Avatar answered Oct 08 '22 14:10

Pointy