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.
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.
Table of Contents
About This Book
Data Types, Variables and Expressions
Flow Control Statements
Creating, Accessing, and Manipulating Arrays
►Defining and Calling Functions
Defining Your Own Functions
Defining Your Own Functions - Example
Calling Your Own Functions - Example
Passing Parameters by Value or by Reference
Function Parameters Are Passed as Local Copies
Function Parameters Are Passed as Local Copies - Example
►Global and Local Variables - Scope Rules
Global Variables - Examples
Local Variables - Examples
Collision of Global and Local Variables - Examples
"return" Statement and Return Value
Server-Side and Client-Side Web Scripting
Introduction to Objects
Defining Your Own Object Types
Inheritance of Properties and Methods through the Prototype Object Chain
Using Functions as "Function" Objects
Introduction to Built-in Object Types
W3C's Document Object Model (DOM) Specifications
Full Version in PDF/EPUB