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 Simplify Repetitive Tasks with Loops `do ... while` Loops

do.....while

I have read in the book that the syntax do..while rarely used, because while ordinary clearer - there does not have to look through the eyes of the condition and puzzle why it is checked at the end of. It's true?

1 Answer

I feel the question might need some rewording, but if you are asking if a do while loop executes the code within the loop before checking the condition then the answer would be yes.

The only time I really used a do while loop was in menu selection. But this was in Java and an admin console part of the program.

Basically I ran the do while loop as long as the menu selected was not 0

The user was prompted something like:

(1) Create Database (2) View Database (3) Delete Database (0) Quit

Then I had the console grabbing the keyboard output inside the do while loop and a switch statement that would execute the appropriate code depending on what they inputed. If you would like I could write up some code and show you what I mean, but I am sure there are a few other reasons why you would use a do while

Mainly use a do while when you want something to execute at least once regardless if the condition is true of false

"do-while is a loop with a post-condition. You need it in cases when the loop body is to be executed at least once. This is necessary for code which needs some action before the loop condition can be sensibly evaluated." ~stackoverflow

Thank you so much for a detailed answer!

You are very welcome Iliya Narsiya!