New course! Every coder should learn Generative AI!
Try a free lesson+ 7
Why is the value of "i" in my code 5 after setting its value to be less than 5 in the loop?
for(i=0; i<5; i++); {} document.write(i);
9 Answers
+ 9
Mofey Consider the steps of the for loop...
1. Check if the break condition is true.
2. Execute the block or exit the loop.
3. Iterate the value of `i`.
In this loop, the break condition is true while i < 5. This means that the block of code in the loop will run when i is 0, 1, 2, 3, and 4.
Now... you are probably thinking that `i` should be 4, not 5. But, remember, `i` needs to be incremented to 5 for the break condition to occur. This last increment happens in step #3 with i++, after step #2 executes the block for the last time, when `i` was 4.
Therefore, `i` reflects the value at the time of the break condition, which is 5.
+ 12
The condition in the for loop is that the code will execute if and only if value of i is less than 5... Until this condition is true (i is less than 5 in the first 5 steps) the code will execute... When i reaches 5, i is no longer smaller than 5... So the statement that i<5 becomes false... And then when the condition is checked, there are no true conditions...
I think Qasem meant to say that...🙂
+ 9
Suppose that i is 4. Then i++ increments it by one and when condition is checked there is no true condition and loop won't be executed. But i is 5 now
+ 8
Wow David Carroll, once again, Woaw, thank you very much for that explanation because I was actually thinking that the loop is meant to stop at 4 since `i` was set to be less than 5
+ 7
The loop runs as long as `i` is smaller than 5. It stops when `i` hits 5.
So, for the loop to stop, `i` has to become 5 - otherwise `i` would be smaller than 5 and the loop continues.
+ 7
Condition is : i<5. When i==5, this condition is false.
+ 5
Qasem, what do you mean by "when condition is checked, there is no true condition" ??
+ 5
For loop has three parts.
Initial value, counting, and condition check.
Those are executed in order which I wrote.
For (initial value; condition check to run loop; counter)
+ 4
I is OUTSIDE THE LOOP (4 ++ = 5) 🤗🤗