We use self executing function, to manage Variable Scope.
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. (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 and have local scope. Function parameters also count as local variables and are defined only within the body of the function.
var scope = "global";
function checkscope() {
alert(scope);
}
checkscope(); // global
As you see, you can access the scope
variable inside your function,
but, within the body of a function, a local variable takes precedence over a global variable with the same name. If you declare a local variable or function parameter with the same name as a global variable, you effectively hide the global variable.
var scope = "global";
function checkscope() {
var scope = "local";
alert(scope);
}
checkscope(); // local
alert(scope); // global
As you see, variable inside the function, won't overwrite global variables.
Because of this feature, we put the code inside the self executing function,
to prevent overwriting the other variables, when our code get big and big.
// thousand line of codes
// written a year ago
// now you want to add some peice of code
// and you don't know what you have done in the past
// just put the new code in the self executing function
// and don't worry about your variable names
(function () {
var i = 'I';
var can = 'CAN';
var define = 'DEFINE';
var variables = 'VARIABLES';
var without = 'WITHOUT';
var worries = 'WORRIES';
var statement = [i, can, define, variables, without, worries];
alert(statement.join(' '));
// I CAN DEFINE VARIABLES WITHOUT WORRIES
}());
- You can read more about JavaScript on this book: JavaScript: The Definitive Guide, 6th Edition.