In javascript, when would you want to use this:
(function(){
//Bunch of code...
})();
over this:
//Bunch of code...
Self executing function are used to manage the scope of a Variable.
The scope of a variable is the region of your program in which it is defined.
A global variable has global scope; it is defined everywhere in your JavaScript code and can be accessed from anywhere within the script, even in your functions. On the other hand, variables declared within a function are defined only within the body of the function. They are local variables, have local scope and can only be accessed within that function. Function parameters also count as local variables and are defined only within the body of the function.
As shown below, you can access the globalvariable variable inside your function and also note that within the body of a function, a local variable takes precedence over a global variable with the same name.
var globalvar = "globalvar"; // this var can be accessed anywhere within the script
function scope() {
alert(globalvar);
localvar = "localvar" //can only be accessed within the function scope
}
scope();
So basically a self executing function allows code to be written without concern of how variables are named in other blocks of javascript code.