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 JavaScript Loops, Arrays and Objects Tracking Data Using Objects The Student Record Search Challenge Solution

susan corbett
susan corbett
3,060 Points

"While(true)"? Why does this work?

Is it because the value it's testing is the loop's return value? saying essentially "While this loop returns true, do this action?"

So "while" loops work on the parameters of what the loop returns?

4 Answers

A 'while' loop that begins while (true) creates a loop that will continuously run until a break condition. Something like:

while(true)
{
    x++ //do something
    if(x > 100) //until a condition is met
    {
        break; //exit the loop
    }
}

After researching this for awhile it seems like there is a general feeling that while(true) shouldn't be used, but that might be outside the scope of your question.

It might be easier to understand if you think of the parenthetical 'true' as a conditional statement. So:

while(x < y) { x++ }

or in English: while (it's true that) x is less than y, add 1 to x

The 'while' loop tests whether the condition is true and executes the code inside the curlybraces until the condition is false.

rydavim
rydavim
18,814 Points

I've changed your comment to an answer, so that it may be voted on or marked as best answer.

susan corbett
susan corbett
3,060 Points

The 'while' loop tests whether the condition is true and executes the code inside the curlybraces until the condition is false.

Okay, that hits the heart of my question.

In your example, I see that loop is testing a finite thing, the value of the variable x. When simply while(true) is used, what is being tested? The return value of the loop?

Thanks!

susan corbett
susan corbett
3,060 Points

Thank you! Got it. So while(true) doesn't really test anything. It's an infinite loop that will never return false and has to be ended by a break statement!

Got it!

It doesn't test a return value. It's always "true" no matter what.