
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
198
|
Chapter 9: Functions
Local Variables
Variables assigned to a function’s local scope are called local variables. Local vari-
ables, including parameters, are accessible only to statements in the body of the func-
tion in which they are defined and exist only while that function runs. To create a
local variable (other than the parameters that automatically become local variables),
we use the var statement inside any function, like this:
function funcName () {
var temp = "just testing!"; // Declares the local variable temp
}
Local variables are useful for holding information temporarily. Here, for example, we
use the local variable
lastSpacePlusOne to hold an interim result. Like all local vari-
ables, it dies when the function ends:
function getLastWord (text) {
var lastSpacePlusOne = text.lastIndexOf(" ") + 1; // Local
var lastWord = text.subString(lastSpacePlusOne, text.length); // Local
return lastWord;
}
// Displays: "word"
trace(getLastWord("Tell me the last word"));
// Displays: undefined. lastSpacePlusOne is local and not
// available outside the getLastWord() function.
trace(lastSpacePlusOne);
When local variables expire at the end of a function, the memory associated with
them is marked for automatic deletion. By using local variables to store all tempo-
rary values, we can conserve ...