For loop iteration count

let sum = 0 ;
for(let i = 0 ; i <= 9 ; i++ , sum += i);
console.log(sum); // output is 55
let sum = 0 ;
for(let i = 0 ; i <= 9 ; i++){
        sum += i;
}
console.log(sum); // output 45

why first loop is having 11 iteration

0+1+2+3+4+5+6+7+8+9 = 45

this is second ones answer i know this but why first loop is having output 55

Because the loop only stops when i is at least 10. And right after i turns 10, you add it to sum. The condition (second block) however is checked AFTER that third codeblock in the head is executed → so the i=10 is added to sum, before the loop checks if i is bigger than 10.

In fact, because the third block is executed after the body is run, sum actually adds the numbers 1-10, not 0-9.

1 Like