advertisement -- please support sponsors

programming:
local and global variables

The "scope" of a variable refers to the variable's visibility within a program. Variables which are accessible only to a restricted portion of a program are said to have "local scope." Variables that are accessible from anywhere in the program, however, are said to have "global scope."

In JavaScript, variables fall into two major categories: global and local. Global variables are accessible from anywhere in the program and retain their values until the document is unloaded. Local variables, on the other hand, are created during function calls for temporary use and are accessible only within the functions that create them.

In this article I will demonstrate the use of global and local variables in JavaScript, explain the differences between them, and demonstrate why both types are useful. It is assumed that you are familiar with other aspects of JavaScript programming and that you know what a variable is.

global variables

The following JavaScript example creates two global variables (year and month), assigns values to them, and then prints their values:
year = 1997; function make_month_variable () { month = 2; } make_month_variable (); document . write ("year=" + year + " and month=" + month);
If you are familiar with traditional structured programming languages, such as Pascal or C, you might see some strange things in this code:
  1. Variables are not formally declared before values are assigned to them.
  2. Although the variable month is created inside a function, it is not actually used until after the function returns.
Global variables can be created anywhere in JavaScript code, simply by assigning initial values to them.* Once created, global variables can be accessed from any part of the script and retain their values until the document is unloaded.

In JavaScript, newly created variables are assumed to be global, regardless of where they are created, unless explicit measures are taken to make them local. In the example shown above, the variable month is created when the function is called, not defined. After the function returns, however, the month variable retains its definition. (Otherwise, the write statement would result in a JavaScript error.)

In summary, you should use global variables to store values that

If your functions are using global variables that don't satisfy either of these two requirements, then you should consider rewriting them so that they use local variables instead.

local variables

Local variables store temporary variables during a short, well-defined block of code, such as a function, and are accessible only within the block where they are defined. Local variables can only be created in functions; this is done by preceding the first instance of the variable's name with the keyword var. In the example shown below, a local variable named x is created and initialized with the value 5.
function foo ()
{
	var x;
	x = 5;
	.
	.
	.
}
   ...or...   
function foo ()
{
	var x = 5;
	.
	.
	.
}
By the way, function parameter variables are considered local variables. (There are a few exceptions to this rule, but mentioning them here will only make things more complicated. :-)

Local variables are accessible only in the functions where they are created. When functions exit, all of their local variables are automatically destroyed.

global and local variables with the same names

A potential ambiguity arises when two distinct variables -- one global and one local -- have the same names. The JavaScript interpreter resolves this ambiguity by giving priority to local variables whenever possible. Thus, it is possible for global variables to become masked, or hidden from the interpreter's view, when local variables exist by the same names. Although masked global variables retain their values, they are not (easily) accessible until the local variables masking them fall out of scope.

Local variables fall out of scope in two ways:

  1. A function exits and its local variables are automatically destroyed.
  2. A function calls another function, thus suspending the first function and all of its local variables.
In the first case, the variables fall out of scope simply because they cease to exist. In the second case, the local variables are only temporarily out of scope and will become visible again when the called function returns.

Each time a function is entered, a separate "variable space" is created for the function's local variables. Thus, even when a function repeatedly calls itself, the local variable space created for the outer function call is unrelated to the variable space created for the inner function call.

an example

The following example is given to illustrate the behavior of global and local variables. This example will also demonstrate how local variables can mask global variables. Consider the JavaScript code shown below:
function function_1 () { var x = 5; document . write ("<br>Inside function_1, x=" + x); function_2 (); document . write ("<br>Inside function_1, x=" + x); } function function_2 () { document . write ("<br>Inside function_2, x=" + x); } x = 1; document . write ("<br>Outside, x=" + x); function_1 (); document . write ("<br>Outside, x=" + x);
When executed, the values of two distinct variables, both named x, will be printed. The following table describes the process:

explanation illustration program output
A global variable named x is created and initialized with the value 1. This value is output to the document. Outside, x=1
function_1 is called. As it executes, a local variable named x is created and set to 5. Because this local variable has the same name as the global variable, the global variable is masked and the function's first write statement outputs the value 5, not 1. Inside function_1, x=5
function_1 calls function_2. Because function_2 cannot see function_1's variables, the reference to x in function_2 is interpreted as a reference to the global variable. Thus, a value of 1 is written to the document. Inside function_2, x=1
When function_2 returns, however, function_1 continues where it left off, and the local variable comes out of hiding. Thus, a value of 5 is again written to the document. Inside function_1, x=5
Finally, when function_1 finishes, the local variable x is destroyed and the global variable is the only one left. Thus, a value of 1 is written to the document. Outside, x=1

conclusion

So what's the big deal about local and global variables? Why not make them all global and be done with it?

Decades ago, when system memory was expensive, local variables were used to conserve memory. Variables were created on demand, used for a while, and then destroyed so that the memory used to store their values could be recycled for other variables. Although this once was a pretty good reason for using local variables, it is hardly worth mentioning in a JavaScript environment. There are better reasons than this.

Experienced programmers support a programming philosophy called "the principle of least privileges." This philosophy says that if the accessibility of a program resource, such as a function or variable, is restricted to just those portions of the program where such accessibility is required, then the programmer is less likely to introduce errors into the code without noticing them quickly.

Another good reason for using local variables is that less effort is required to keep track of variable names. Since each function call results in the creation of a new variable name space, different functions can use the same variable names without treading on each other's variables.

For these reasons, it is considered good programming practice to use local variables whenever possible. In JavaScript, this means your functions should use local variables to store temporary values that will not be needed after the function returns -- loop variables, for example. Adopting a habit of using local variables whenever possible will help you avoid subtle JavaScript coding errors that might not be noticed until after your web page is published.

Charlton Rose
17 Feb. 1997