Daniel Mizerski Daniel Mizerski - 6 months ago 14
Javascript Question

Double for loop in JavaScript

var
startx = 0,
starty = 0,
endx = 12,
endy = 100;

for(startx;startx <= endx; startx+=1){
for(starty; starty <= endy; starty+=1){
console.log(startx, endx, starty, endy);
}
}


Expected output:

0, 12, 0, 100
0, 12, 1, 100
0, 12, 2, 100
...
0, 12, 100, 100
1, 12, 0, 100
1, 12, 1, 100
...
12, 12, 100, 100
;EOO


Output on Chrome 39+

0, 12, 0, 100
0, 12, 1, 100
0, 12, 2, 100
...
0, 12, 100, 100


So the problem is the first for loop does not iterate over startx variable.

Could you tell me why it does not iterate?

Answer

It's because starty is not reset after the first iteration:

You want:

var startx = 0,
    starty = 0,
    endx = 12,
    endy = 100;

for (; startx <= endx; startx++) {
    for (starty = 0; starty <= endy; starty++) {
        console.log(startx, endx, starty, endy);
    }
}

I also simplified startx+=1 to startx++, same goes for starty.

I will also suggest to get into the habit of writing each var statement on it's own:

var a;
var b;

This makes it easier to stop on when debugging. Try stepping into def() without stepping into abc().

var a = abc(),
    b = def();

How is a for loop broken down:

The for loop is broken down into 3 parts:

for(initial; condition; after)

initial is called before the loop, can safely be omitted.
condition is called just before running the code in the loop, will always be true if omitted
after is called after the code in the loop same as writing:

for(var i = 0; i < 10;) {
  // code
  i++;
}
Comments