JavaScript Tutorials - Herong's Tutorial Examples
Dr. Herong Yang, Version 2.00

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 by Dr. Herong Yang, http://www.herongyang.com/
-->
<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

Sections in This Chapter

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

Dr. Herong Yang, updated in 2008
Collision of Global and Local Variables - Examples