February 28, 2000 - Global vs Local Variables | WebReference

February 28, 2000 - Global vs Local Variables

Yehuda Shiran February 28, 2000
Global vs Local Variables
Tips: February 2000

Yehuda Shiran, Ph.D.
Doc JavaScript

JavaScript differentiates between global and local variables. A variable that is defined in the main script somewhere with or without the prefix 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 i=2. In this way we insure i does not share the operations with another i somewhere else.

Learn more about the recursive usage in JavaScript in Column 58, The Doc Dialer.