0

For Loop

Why is it in the FOR LOOP the increment is only considered after the first iteration? Example: Let sum = 0; For (i = 1; i <= 3; i++) { if (i==2) { continue; } sum+=i; } console.log(sum); Answer is: 4 Question is initially i = 1, the condition is true, why is i++ skipped before going into IF STATEMENT? Shouldn’t i be incremented before going into IF STATEMENT in the first iteration, which will mean that it’ll go in as 2, and IF becomes TRUE and sum+=i skipped, so sum answer becomes 3?

20th Dec 2023, 1:54 PM
Nosipho Mbele
Nosipho Mbele - avatar
2 Answers
+ 4
It seems you misunderstanding how the for loop works. for (i = 1; i <= 3, i++) It means i starting as 1, if i is less than or equal to 3, do the codes below. When finished, increase i by 1. Therefore in your example: i = 1, which is less than or equal to 3, so sum + 1, and then i increase by 1. In the next loop, i = 2, which is also less than or equal to 3. However the if statement say if i equals to 2 it will be skipped. So it is skipped and i increase by 1. In the next loop, i = 3, which is also less than or equal to 3, so sum + 3 and i increase by 1 again. In the next loop, i = 4, it is greater than 3 and exit the loop. At this point sum is 4, so it prints 4.
20th Dec 2023, 2:58 PM
Wong Hei Ming
Wong Hei Ming - avatar
+ 1
Thank you Wong Hei Ming for your answer, especially this line made more sense in spoken language 😅 “It means i starting as 1, if i is less than or equal to 3, do the codes below. When finished, increase i by 1.” Thank you.
20th Dec 2023, 5:05 PM
Nosipho Mbele
Nosipho Mbele - avatar