Excercise 6.3 The For Loop


#1

Hello everybody,

it is really difficult for me to wrap my head around the way for-loops work. I found an explanaition here: [FAQ] and some Explanations about Loops


for(initalize;condition;manipulate){
statements;
}

manipulate :this part is executed after the execution of
the stuff in the {} and normally its used to change the value of the
counting variable to get it nearer to the stopping value e.g. i++


Could someone explain to me, why “manipulate” is executed after the statements in {} even though it is written before the statements in {}. Why does JavaScript just “skip” it and then execute it in the end? I could just take it as a fact, but it would really help me to understand the logic behind it, because for me it is completely illogical atm.

Thanks in advance


#2

before would be very confusing, lets do an example:

for (let i = 0; i < 5; i = i + 1){
  console.log(i);
}

if i = i + 1 would be before the code in the loop block (between the {}), the first value logged would be 1, which is very confusing given we specified 0 as starting value.


#3

Hello stetim94,

thank you for responding. But if you break the code down in single steps, it would be:

Step 1: assign “0” to “i”
Step 2: check if “i < 5”
Step 3: add “1” to “i”
Step 4: console.log(i)

But JavaScript kind of executes the code as Step 1, 2, 4, 3.

Please dont get me wrong. I really dont want to be a pedantic about it. I just want to understand why JS does it in this order.


#4

did you run the code i gave you? it gives:

0
1
2
3
4

if i += 1 was done as third, the output would be:

1
2
3
4
5

which is just very confusing.


#5

I just wanted to edit my post when you already replied. I think I just got myself into a corner. And understood where I went wrong the second I hit “reply”. I misunderstood what “let i = 0” really does and from there on it went south.

Thanks a lot for the fast reply. It’s really appreciated.