JavaScript

Alanis Chua
Alanis Chua
1,323 Points

additional notes on while loop

"test condition is not true at the beginning, then the loop will never run" what does this mean?

"If the test condition is always true, the loop runs forever, and it never stops." is there any example to show this?

2 Answers

Osaro Igbinovia
PRO
Osaro Igbinovia
Pro Student 6,450 Points

It simply means that if the test condition in a while loop is false right from the start, the while loop will never run.. The only way a while loop can run is if the test condition is true even if it's just for the first looping.

var i = 0;
while (i >= 0) {
     console.log('I am an endless loop');
     i += 1;
}

The above snippet of code is an example of an endless loop. Since the 'i' variable is 0 at first and increases by 1 each time the loop runs, 'i' will count from 0 to 1 to 2 to 3 and so on. What makes it an endless 'while' loop is the test condition, the loop will check if it's true each time the loop runs and it will always be true because 'i' is equal to zero at the start and will consequently be greater than zero till infinity (i+= 1).

Dave varmutant
Dave varmutant
9,587 Points

"test condition is not true at the beginning, then the loop will never run" what does this mean? The while and for loops check the condition prior to executing the code block. So, when the condition is false, nothing happens. The do while, on the other hand executes the code before checking the condition, so regardless of the condition, the code block is always executed at least once.

"If the test condition is always true, the loop runs forever, and it never stops." is there any example to show this? Each time through the loop the condition is checked. If nothing happens to stop the loop (like a counter reaching a value, the break command or something else to set the condition to false) then it never stops - infinite loop.