Chapter 9
Functions and Variable Scope
Variable Scope and Storage Class
All JavaScript variables have two attributes:
JavaScript implements these characteristics slightly differently from other programming
languages.
The scope of a variable describes the area of the script where the variable is valid.
You can refer to the variable only in this area—it does not exist elsewhere. The scope
of a global variable is the entire script. You can access it anywhere between the <SCRIPT>
and </SCRIPT> tags and other scripts that are executed after the variable
definition (including preceding event handler scripts). In JavaScript, you can declare
global variables with or without the keyword var. It does not affect the scope of
the variable at all.
A local variable is declared in a function. It can only be referenced by
statements inside that function. Therefore, a global variable may have the same name as a
given local variable. In the scope of a local variable (the function where it is defined),
only the local variable exists. Outside that function, only the global one exists. A local
variable must be declared inside a function using the keyword var. If omitted, the
variable is assumed global. The following script segments show how a variable’s scope
influences various results:
// Script 1
function test() {
age = 43
}
age = 11
test()
document.write(age + "<BR>")
// Script 2
function test() {
var age = 43
}
age = 11
test()
document.write(age + "<BR>")
The only difference between these scripts is the statement inside the function. In the
second script segment, we use var to define the variable age, whereas in
the first statement, we simply state the desired variable name.
The output of the first script is:
43
and the output of the second script is:
11
Take another look at the first script and try following the execution thread. The value
11 is assigned to the global variable age and the function is invoked.
Notice that the word var is not used inside the function. Therefore, the variable
age in the function is assumed global, and the value 43 is assigned to
the global age. Therefore, the result is 43.
In the second script, we assign the value 11 to the variable age, and
then call the function. The var word means that the variable age, which
is defined inside the function, is local. It does not exist beyond the function, so the
value of the global variable age (the one defined before the function call) is
not modified by the assignment statement inside the function. The last statement of the
script prints the value of the global variable age, because it is the only
variable named age in that scope. Therefore, the script’s output is 11—the
global variable’s initial value.
Once declared with the var keyword, additional statements referring to the
variable should not issue that prefix. Here is the previous script with an additional
statement inside the function:
// Script 2 (additional statement in function)
function test() {
var age = 43
age = 58
}
age = 11
test()
document.write(age + "<BR>")
Once again, the output of the script is 11. The variable inside the function
is declared with the keyword var. From that point on, the scope of the variable
is only the function test(). It does not exist outside the boundaries of that
function, so the script’s output is the value of the global variable named age,
not the local one.
Note that the statement
age = 11
in the previous script segments is equivalent to
var age = 11
because the var keyword is optional for global variables.
Here’s another script segment that deals with various scopes:
function test() {
age = 5
}
test()
document.write(age + "<BR>")
The script’s output is 5, because the variable age is declared
inside the function as a global one (without var), so its scope is the entire
script. The next script generates quite an unexpected output:
function test() {
var age = 5
}
test()
document.write(age + "<BR>")
Rather than generating an output, this script generates an error (see Figure 9-1)
because age is a local variable, whereas the printing statement is not located in
its scope.
Figure
9-1. An error dialog box that appears when referring to a
variable that does not exist (IE shows a similar message).
The variable’s storage class may be either permanent or temporary. You
cannot modify this attribute directly, the way you can declare the variable as static
in other languages such as C++. The storage class of a variable in JavaScript depends only
on its scope. Local variables are temporary, while global variables are permanent.
Permanent variables exist throughout the script and even in other scripts. Even after a
script has terminated, the global variable remains, and is only discarded when the page
unloads. Temporary variables are allocated on the stack (a section of memory) when
a function is called. The space used by a function’s local (temporary) variable is
returned to the stack at the end of the function execution. After a local variable
“dies,” it leaves free memory space for other variables and objects to come.
Avoid declaring large local data structures such as arrays (discussed in the following
chapters). If you try to allocate too many temporary variables or extremely large ones,
you are likely to receive an error (usually called stack overflow). For the same
reason, avoid passing large data structures over to a function. It is better to use global
variables for such tasks.
Function parameters are identical to local variables. They exist only inside the
function, and do not affect any variable outside it. You can refer to function parameters
as if they were variables that you declared at the beginning of the function and
initialized them with appropriate values. The following script segment demonstrates this:
function test(age) {
age = 5
document.write(age + "<BR>")
}
test(6)