0

Can someone help me understand the statement below:

The While Loop If you forget to increase the variable used in the condition, the loop will never end.

2nd May 2018, 3:54 PM
Augustine Agyemang-Duah
Augustine Agyemang-Duah - avatar
3 Antworten
+ 4
var i=1; while(i<10) { alert("hello"); } //there is nothing incrementing i so i stays 1 forever.and 1 will forever be less than 10 soo loop runs forever var i=1; while(i<10) { i++; alert("hello"); } since i is being incremented in the loop it will at some point become 10 so loop stops running
2nd May 2018, 3:57 PM
᠌᠌Code X
᠌᠌Code X - avatar
+ 2
Sure! Let's say I have something like this: var i = 0; while (i < 5){ console.log(i); i++; } The i++ statement makes sure that i value gets increased. So I will get at the console: 0 1 2 3 4 until i becomes 5 and the condition in the loop i < 5 is no longer True and we exit the loop Now let's suppose that I do not do i++ in the loop and i keeps its initial value 0. I will have printed: 0 0 0 0 0 0 forever because the condition in the loop i < 5 will always be True and we will never exit. Makes more sense?
2nd May 2018, 3:58 PM
cyk
cyk - avatar
+ 1
thanks so much. I'm OK now
2nd May 2018, 4:19 PM
Augustine Agyemang-Duah
Augustine Agyemang-Duah - avatar