JavaScript Tutorials - Herong's Tutorial Examples - 2.33, by Herong Yang
Collision of Global and Local Variables - Examples
This section provides a tutorial example on how JavaScript handles local variables collide with global variables.
To see JavaScript handles global and local variables collide with identical names inside and outside functions, I wrote the following tutorial example:
<html> <!-- Variable_Collision.html Copyright (c) 2008 HerongYang.com. All Rights Reserved. --> <head><title>Variable Collision</title></head> <body> <pre> <script type="text/javascript"> var tempVar; tempVar = "Bird"; tempNoVar = "Fish"; scopeCheck(); document.write("\n\nAfter function call:"); document.write("\n tempVar = " + tempVar); document.write("\n tempNoVar = " + tempNoVar); function scopeCheck() { var tempVar; tempVar = "Bird"; tempNoVar = "Fish"; tempVar = tempVar + " - Updated"; tempNoVar = tempNoVar + " - Updated"; document.write("\n\nUpdated value in function:"); document.write("\n tempVar = " + tempVar); document.write("\n tempNoVar = " + tempNoVar); } </script> </pre> </body> </html>
This tutorial example tests two sets variables. One set introduced outside the function, and one set inside the function. Names of variables in one set collide with the other set. Two "tempVar" declared with "var" statements stay as two variables. But two "tempNoVar" auto-declared without "var" statements become one variable. See the output:
Updated value in function: tempVar = Bird - Updated tempNoVar = Fish - Updated After function call: tempVar = Bird tempNoVar = Fish - Updated
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