February 28, 2000 - Global vs Local Variables
February 28, 2000 Global vs Local Variables Tips: February 2000
Yehuda Shiran, Ph.D.
|
var
is a global variable. Variables that are used in functions without the var
prefix are also global. The problem with global variables is that you sometimes may not be aware that two variables are actually the same. One example is the index counter i
. If you don't define i
with the var prefix to make it local, two index counter i
in two different functions are actually the same. Things get sticky even more when you are coding a recursive function. You must use local variables or else you'll share variables that you were not planning on. Here is an example for a recursive function:
function updateBoard(trieNode) {
if (trieNode[1]) {
addEmployeeToDisplay(trieNode[1]);
}
for (var i=2; i<=9; i++) {
memberNode = trieNode[i];
if (memberNode) {
updateBoard(memberNode);
}
}
return;
}
Notice that we put the var prefix in front of Learn more about the recursive usage in JavaScript in Column 58, The Doc Dialer.
i=2
. In this way we insure i
does not share the operations with another i
somewhere else.