JavaScript Tutorials - Herong's Tutorial Examples - 2.33, by Herong Yang
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
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