Self-Executing Anonymous function JavaScript
(function(){
//Bunch of code...
})();
Its all about variable scoping. Variables declared in the self executing function are, by default, only available to code within the self executing function. This allows code to be written without concern of how variables are named in other blocks of javascript code.
JavaScript has function level scoping. All variables and functions defined within the anonymous function aren’t available to the code outside of it, effectively using closure to seal itself from the outside world.
To allow access to a variable or function, we need to expose it to the global ‘window’ object.
(function(){
var foo = 'Hello';
var bar = 'World!'
function baz(){
return foo + ' ' + bar;
}
window.baz = baz; //Assign 'baz' to the global variable 'baz'...
})();
console.log(baz()); //...and now this works.
//It's important to note that these still won't work:
console.log(foo);
console.log(bar);
One of the major benefits of this pattern, as seen on the last two lines of the previous example, is that you can limit access to variables and functions within your closure, essentially making them private and only choosing to expose an API of your choice to the global scope.