-4

I am confused about this for loop:

for (var i=0,j=0;i<4,j<20;i++,j++) {
    a=i+j;
}
console.log(a);

Why is the answer 38? Before I ran it, I thought the answer would have been 6.

Qantas 94 Heavy
  • 15,750
  • 31
  • 68
  • 83
Priest.K
  • 1
  • 1

2 Answers2

0

Try looking at the valus of i and j you will see they will both be 19 when the loop finishes even if the condition that stops the loop happens to be on j

Open your debugger and run the following

for(var i=0,j=0;i<4,j<20;i++,j++){ 
  ab=i+j; 
  console.log("i", i); 
  console.log("j",j); 
  console.log("a", a); 
}
Victory
  • 5,811
  • 2
  • 26
  • 45
0

You want to use && not the comma operator. I added more console.log steps to show the intermediate steps.

for(var i=0,j=0;i<4 && j<20;i++,j++){
  a=i+j; 

  console.log("a: "+a+ " i+j:" + (i+j))
}
console.log(a);

In the original version of your for loop compare the comma separated conditions to the && separated conditions:

for(var i=0,j=0;i<4,j<20;i++,j++){
   a=i+j;
   console.log("(i<4, j<20): " + (i<4, j<20))
   console.log("(i<4 && j<20): " + (i<4 && j<20))

 }
 console.log(a);
dr jimbob
  • 17,259
  • 7
  • 59
  • 81