Search This Blog


Monday, April 21, 2008

Beware of "Variable Reuse" inside a Loop!

Here's the code, see whether you can diagnose the problem or not?

for(var i=0; i < sortArray.length; i++){
t= sortArray[i];
if(ts[t] < cloudMin){

var fs = s(minFontSize,maxFontSize,ts[t]-ta,tz);
li = document.createElement('li'); = fs+'px'; = '1';
a = document.createElement('a');
a.title = ts[t]+' Posts in '+t;

for (var i=0;3 > i;i++) {
} = 'rgb('+c[0]+','+c[1]+','+c[2]+')';
a.href = '/search/label/'+encodeURIComponent(t);
if (lcShowCount){
span = document.createElement('span');
span.innerHTML = '('+ts[t]+') ';
span.className = 'label-count';
else {
abnk = document.createTextNode(' ');

I can't, at least not at a first glance.

The problem with this code is that the variable i is used twice, once as a counter in the outer loop, another time as a a counter to loop over the C array. So whenever the program reaches this section:

for (var i=0;3 > i;i++) {

the variable i will be reset to 0. Whenever the program leaves that section, the i will always be 3, making the above program execution an infinite loop!

I encountered this problem when I was trying to change my cloud tag into Technorati style by modifying the code snippet given in this post. Since I didn't have any web development tools, such as firebug installed, I couldn't step through the code. My blog post would just hang after I made the changes and published it. It was only after a lot of alert('') traces that I got the problems figured out.

Maybe this was why .Net introduces scopes for variables inside loops. An equivalent C# program would detect that the i was declared twice and flag it as a compilation error. If the i was declared outside the loop, then the above error may still slip through, which is why one should always use

for (int i=0; i<10;i++)

instead of the old C++ way

int i=0;
for(i=0; i<10;i++)


Anonymous said...

Two things that may help you as you start your programming career:
1) Always use different var names for loops: ie. i1,i2... or just i,j,k etc.
2) Program in Java - always catches these newbie errors.

Good Luck!

Soon Hui said...

Thanks anonymous,

I agree with you, especially on the second point.