0

Loop Logic

Hi, I have a very basic question. Why will the starting value in a loop also be spit out from console.log if at the end of the first iteration, the value is already changed to i+=1? An example below where the loop counts up to 10, starting with 0 and not 1. In my head, the first value resulting of the loop should already be 1. I don’t get it. for(let i=0; i<=10; i+=1) {console.log(i);}

29th Nov 2022, 12:19 PM
SAH
SAH - avatar
3 Answers
+ 1
You answered in your question: the variable gets incremented at the END of the iteration. So everything inside the loop is executed BEFORE the variable gets incremented. And it's logic: we set the variable in the start value. So we expect execution to start with this value.
30th Nov 2022, 2:40 AM
Emerson Prado
Emerson Prado - avatar
29th Nov 2022, 12:36 PM
arturop200
arturop200 - avatar
+ 1
Thank you Emerson Prado . I get it now!
30th Nov 2022, 6:23 AM
SAH
SAH - avatar