Global and Local Variables - Scope Rules
This section provides a quick description of global variables and local variables. Basic rules about variable scopes are provided.
1. Script Level Scope - A variable declared with a "var" statement outside any function has a scope at the script level. A variable with a script level scope, called global variable, is valid everywhere in the script, even inside functions.
2. Function Level Scope - A variable declared with a "var" statement inside a function has a scope at the function level. A variable with a function level scope, called local variable, is valid only inside the function where it is declared.
3. Auto-declaration - If a variable is used without the "var" declaration statement, it will be automatically declared with the script level scope, becoming a global variable, event it is used inside a function. But using this approach of auto declaration global variables is not recommended.
4. Collision - If a variable is explicitly defined in a function has the same name as a variable defined outside the function, the variable outside the function become in-accessible within this function.
There are some interesting consequences of those rules:
See the next section for examples of how variable scope rules are applied.
Table of Contents