Javascript tip

I was having the most unusual problem in a function that used a for loop to find selected items in a html select list. My iterator variable “i” was for some reasen ending up with a value higher than the for loop would allow.

As it turns out, if you declare a variable without using the “var” keyword, that variable has global scope.

Case in point:

function pressRemove() {
  fromBox = selBox;
  toBox = allBox;
  for (i=fromBox.length-1;i>=0;i--) {
    if (fromBox.options[i].selected) {
	  addOpt(toBox,fromBox.options[i].value,fromBox.options[i].text,2);
	  fromBox.remove(i);
	}
  }
}

The function addOpt includes it’s own for loop, also using a variable named i. That inner for loop was overwriting the value in this for loop!

...
  for (var i=fromBox.length-1;i>=0;i--) {
...

By changing all the for loops to declare their variables, the problem was solved. Personally, I think that is a really stupid “feature”, but since both IE and Firefox do it, it is expected.

Leave a Reply

Your email address will not be published. Required fields are marked *