∟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 HerongYang.com. All Rights Reserved.
-->
<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

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