Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Alanis Chua
Alanis Chua
2,830 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

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 StSomeWhere
Dave StSomeWhere
19,870 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.