JavaScript Tutorials - Herong's Tutorial Examples - 2.33, by Herong Yang
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.
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:
See the next section for examples of how variable scope rules are applied.
Table of Contents
ECMAScript Language Specification and JavaScript Dialects
Data Types, Variables and Expressions
Creating, Accessing, and Manipulating Arrays
►Defining and Calling 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
Collision of Global and Local Variables - Examples
"return" Statement and Return Value
Web Browser Supporting JavaScript
Server-Side and Client-Side Web Scripting
Defining Your Own Object Types
Inheritance of Properties and Methods through the Prototype Object Chain
'jrunscript' - JavaScript Shell Command from JDK
Using Functions as "Function" Objects
Introduction to Built-in Object Types
W3C's Document Object Model (DOM) Specifications