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 Multiple Items with Arrays Useful Array Methods

Ivana Lescesen
Ivana Lescesen
19,442 Points

Why is the while (true) ?

Hello why is the while loop set to true?

3 Answers

Jennifer Nordell
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree
Jennifer Nordell
Treehouse Teacher

There are two reasons a while loop will exit. Either the condition to be evaluated becomes false, or a break statement is encountered. In his example, he's intentionally setting up an infinite loop so that it will continually ask the user what they want to do. Do they want to list the products or add a product etc. But when the user types "quit", the break statement will execute causing the while loop to exit.

edited for additional note

He briefly explains this at 3:56 in the video :smiley:

Hope this helps! :sparkles:

Can't you instead of a while(true) use instead a 'do'?

Jennifer Nordell
seal-mask
.a{fill-rule:evenodd;}techdegree
Jennifer Nordell
Treehouse Teacher

The only difference there would be that the block of code inside the do would be guaranteed to run once. The while(true) would still be the condition to evaluate at the bottom.

Great, thanks for the tip!