Make your own free website on

Variable scope in for loop

When we handle a 2D array, we will assing different index variable to access the array, such as:

for(var i=0;i<20;i++){
    for (var j=0;j<20;j++){
        //do something to array[i][j];

Sometimes, we are not going to handle a 2D array. It just a loop. For example, I have a cube. Cube has 6 faces. Each face has 4 corners.

In C, the index variable i is kept within the for-loop block, so I used to index a loop always by i. Usually the var i in the inner loop will not affect the i in the outer loop;

for (var i = 0; i<200; i++) {
    //a long script
    for (var i = 0; i<50; i++) {
        //do things

In action script or javascript, the var i in the outer loop will be affected by the i in the inner loop.

I got problems from this several times.