This section provides a quick description of global variables and local variables. Basic rules about variable scopes are provided.
When functions are used in a JavaScript code, variables are declared in two scope levels.
Here are some basic rules related to variable scope:
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:
The nice thing about rule #1 is that variables defined the main code are automatically
accessible in all procedures. You don't have to pass them as reference arguments to
share them in a procedure.
The bad thing about rule #2 is that if you are using temporary variable in a procedure
without explicit declaration, you could accidentally change the value of a global
variable of the same name.
Rule #3 helps us to avoid the bad impact of rule #3, if you declare all temporary
variables explicitly in procedures.
See the next section for examples of how variable scope rules are applied.