0
Javascript For Loop (Beginner)
Hi, I want to ask, why the value of var I become 11 in this code? var i = 5; for( i = 1; i <= 10; i++){ // zero code } console.log(i); Shouldn't it be 10? I'm so confused, may someone can explain it to me about how it works. Thanks in advance 🙏🙏 https://code.sololearn.com/WQRUxrAEbR06/?ref=app
4 Antworten
+ 2
You have the condition that i <= 10, so when the variable i is 10, the condition is true (10 is less than or equal to 10). The i++ is executed then.
It breaks when i = 11 (11 is NOT less than or equal to 10).
Thus you end up with 11.
+ 2
Yeah, that's intended.
When i becomes 10, it enters the for loop, executes whatever is inside, then going back up becomes 11.
When i becomes 11, it does not enter the for loop, exiting it completely.
The final value for i ends up being 11.
Try experimenting with the condition. To get your desired output, simply change it to i < 10
What happens if you place i > 10, or i != 10 ..? Don't worry about breaking your code, as long as you experiment and figure out what is happening, (nothing like a good google search or ask another question around here)
+ 1
LDSD thanks for answering,
So the value of I is actually 11 but it didn't show up in the for loop (if I put console.log(i) inside for loop) because it breaks the condition.
But if I put console.log(i) outside the loop it will give me 11.
Is that how it works? Sorry if I still got it wrong 😓
+ 1
LDSD Yeah I will experiment more with loops, Thanks 🙏🙏