This should help you understand:
(function(){
var name;
var scope1;
// Here you can use scope1 and name
(function(){
var name; // <------------------------
var scope2; // |
// |
// Here you can use scope1,scope2, and name
(function(){
var name; // <------------------------------
var scope3; // |
// |
// Here you can use scope1,scope2,scope3, and name
})();
})();
})();
// Any\variable declared outside of any function scope is in the global scope.
// A variable declared here can be accessed by window.name from any scope
var name = 5;
So in this snippet, 3 scopes are created by the three functions and in the innermost you can access the variables that have unique names (scope1,scope2, and scope3) as well as the local variable name
, which is a separate name from the one it the middle scope. Reusing variable names like that to prevent access to the variable in an outer scope is called shadowing.
Note that a variable that is not declared with the var
keyword is auotmatically assumed to be in the global scope. It is a bad practice to declare many variables in the global scope as they can easily conflict with other scripts.