0

How is the js for loop sum 55 and not 45?

let sum = 0; for (let i = 0; i <= 9; i++, sum += i); console.log(sum);

21st Jun 2021, 10:25 AM
richard honour
richard honour - avatar
4 Respostas
+ 3
richard honour If you do like that inside loop then both i++, sum += i will work same time but if you do like this then sum += i will work after checking condition so sum will be only 45. let sum = 0; for (let i = 0; i <= 9; i++) { sum += i; } console.log(sum);//45
21st Jun 2021, 10:38 AM
A͢J
A͢J - avatar
+ 2
richard honour Because we are doing sum += i after i++ so when i <= 9 will be true then after i++, sum = 45 + 10 = 55
21st Jun 2021, 10:30 AM
A͢J
A͢J - avatar
+ 1
Thanks never thought bout it that way... ☺
21st Jun 2021, 10:32 AM
richard honour
richard honour - avatar