THE PASZ.COM BLOG

Monday, July 25, 2005

Programming Gotcha: Locally Scoped Variables

The following note applies to JavaScript and ActionScript (but not Java).

JavaScript does something funny with local variables that are within a local block (if...else, while, etc.) Instead of cleaning up the variable at the end of your block, the variable persists until the end of the current function (or until it is redefined. For example, consider the following code.

if (true){
  var i = 100;
  alert(i); // displays 100
}
alert(i); //Expected: i is undefined. Actual: displays 100.

This is not a big deal in most situations, unless you're dealing with code where variable names are frequently re-used. For example, consider the variable name collision here:

var i = 10;
if (true){
  var i = 100;
  alert(i); // displays 100
}
alert(i); //Expected: displays 10. Actual: displays 100.

This problem can be avoided if you're careful not to re-use variable names. But it is something to be on the look out for if you're trying to fix some spaghetti code.

2 Comments:

Post a Comment

<< Home