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

 About This Book

 Introduction to JavaScript

 ECMAScript Language Specification and JavaScript Dialects

 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

 Web Browser Supporting JavaScript

 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

 'jrunscript' - JavaScript Shell Command from JDK

 Using Functions as "Function" Objects

 Introduction to Built-in Object Types

 W3C's Document Object Model (DOM) Specifications

 AJAX (Asynchronous JavaScript And XML)

 References

 Full Version in PDF/EPUB