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.
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.
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);
}
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);