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

Yehuda Shiran, Ph.D.
Doc JavaScript

Developer News
Microsoft Shows Off Silverlight 4, IE9 Plans
Metasploit Expands Vulnerability Test Framework
HyperCard Reborn?

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.


People who read this tip also read these tips:

Look for similar tips by subject:

internet.commediabistro.comJusttechjobs.comGraphics.com

Search:

WebMediaBrands Corporate Info

Legal Notices, Licensing, Permissions, Privacy Policy.
Advertise | Newsletters | Shopping | E-mail Offers | Freelance Jobs

webref The latest from WebReference.com Browse >
Rolling Out Your Own HTML Application Version Control · HTML 5: Client-side Storage · Working with Ajax Server Extensions
Sitemap · Experts · Tools · Services · Email a Colleague · Contact FREE Newsletters 
 The latest from internet.com
Wi-Fi Product Watch, November 2009 · Chip Market Recovering From '08 Collapse · Low-Cost Tools to Kickstart Your New Business