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

Global Variables - Examples

This section provides a tutorial example on how global variables behave inside and outside functions.

To see how global variables behave inside and outside functions, I wrote the following tutorial example:

<html>
<!-- Global_Variable_Scope.html
   Copyright (c) 2008 by Dr. Herong Yang, http://www.herongyang.com/
-->
<head><title>Global Variable Scope</title></head>
<body>
<pre>
<script type="text/javascript">
   var globalVar;
   globalVar = "Cat";
   globalNoVar = "Dog";
  
   scopeCheck();

   document.write("\n\nAfter function call:");
   document.write("\n   globalVar = " + globalVar);
   document.write("\n   globalNoVar = " + globalNoVar);

function scopeCheck() {
   globalVar = globalVar + " - Updated";
   globalNoVar = globalNoVar + " - Updated";
   
   document.write("\n\nUpdated value in function:");
   document.write("\n   globalVar = " + globalVar);
   document.write("\n   globalNoVar = " + globalNoVar);
}
</script>
</pre>
</body>
</html>

This tutorial example tests two global variables: one declared with a "var" statement, and one without. Both variables behave identically. They are valid and accessible inside the function. See the output:

Updated value in function:
   globalVar = Cat - Updated
   globalNoVar = Dog - Updated

After function call:
   globalVar = Cat - Updated
   globalNoVar = Dog - 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
Global Variables - Examples