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);}
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.
+ 1
Well explained in the MDN article. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for#syntax.
+ 1
Thank you Emerson Prado . I get it now!