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

Kieran Corcoran
Kieran Corcoran
11,188 Points

JavaScript do and While loops

Hi,

Would someone be able to give me a better example of why I would use a do loop? I understand the condition run's once but cannot think of an example why I would use this over a while loop.

Thanks

Julien riera
Julien riera
14,665 Points

Hello Kieran,

Don't know if it's the most obvious kind of example but consider this :

You get to a website which asks you for credentials via a prompt (yeah I know...). For this prompt - or whatever - to show at least once you could use a do ... while loop. It appears once, and goes on until you fill the whole form as expected. If you don't, the prompt shows over and over again, forbidding you to go further.

Hope my example isn't moronic !

2 Answers

Kieran Corcoran
Kieran Corcoran
11,188 Points

Hi,

Thank you for your answers.

I think I am making certain things more complex than they need to be and end up completely confusing myself.

Many Thanks

Steven Parker
Steven Parker
229,744 Points

Julien's example seems valid, but to put it a more generic way the factor that would most influence the choice of loop type is the order of performance and testing.

In a do loop, the repeatable code is performed before the test is made to repeat it or not (thus guaranteeing at least one run).

In other loop types the test is made first and then the repeatable code is performed only if the test passed.