JavaScript Tutorials - Herong's Tutorial Examples - 2.33, by Herong Yang
Local Variables - Examples
This section provides a tutorial example on how local variables behave inside and outside functions.
To see how local variables behave inside and outside functions, I wrote the following tutorial example:
<html>
<!-- Local_Variable_Scope.html
Copyright (c) 2008 HerongYang.com. All Rights Reserved.
-->
<head><title>Local Variable Scope</title></head>
<body>
<pre>
<script type="text/javascript">
scopeCheck();
document.write("\n\nAfter function call:");
// localVar is not a valid variable
// document.write("\n localVar = " + localVar);
document.write("\n localVar is not valid");
// localNoVar is a valid variable, auto-declared by scopeCheck()
document.write("\n localNoVar = " + localNoVar);
function scopeCheck() {
var localVar;
localVar = "Apple";
localNoVar = "Orange";
localVar = localVar + " - Updated";
localNoVar = localNoVar + " - Updated";
document.write("\n\nUpdated value in function:");
document.write("\n localVar = " + localVar);
document.write("\n localNoVar = " + localNoVar);
}
</script>
</pre>
</body>
</html>
This tutorial example tests two "local" variables: one declared with a "var" statement, and one without. They behave differently. "localVar" declared with a "var" statement is a true local variable. "localNoVar" auto-declared without a "var" statement becomes a global variable. See the output:
Updated value in function: localVar = Apple - Updated localNoVar = Orange - Updated After function call: localVar is not valid localNoVar = Orange - 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