Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Double for loop in JavaScript

Tags:

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?

like image 445
Daniel Mizerski Avatar asked May 08 '16 19:05

Daniel Mizerski


2 Answers

That was a fun puzzle. It took me a few times before i caught it.

The reason is that starty is not reset after the first iteration and therefore the second for loop will only run once since the condition will always go false.

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++;
}
like image 144
Andreas Louv Avatar answered Oct 05 '22 02:10

Andreas Louv


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

Here your second for loop execute 100 times because your condition is starty <= endy and endy assing the value of 100 . when startx is 0. After finishing the execution of second for loop the startx increment to 1 and again the processed is goes on till it gain the value of 12 . browser's shows the complete results you can console it and scroll down. You will get your desired out put. Hope it useful for you.

like image 42
Akhilesh Singh Avatar answered Oct 05 '22 02:10

Akhilesh Singh