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 Create a `do...while` loop

Pratik Rai
Pratik Rai
6,856 Points

i find this loop tutorial much complicated.

honestly I find these loop tutorial much complicated than others I took before.

2 Answers

Hi Pratik,

The do...while loop just like any other loop construct 'executes a specified statement until the test condition evaluates to false'.

However, the structure of the do...while loop construct as stated below:

do {
   statement
} while (condition);

makes the difference compared to the while loop. In that, the condition is only evaluated after executing the statement; which means that the statement is executed at least once!

For an example, say you want a user to answer the question: "What is the best programming language?". And say you only want the answer to be "JavaScript" and nothing else so you loop the question over and over again until the user finally enters "JavaScript". How do you write this in code?

First let's break this down further:

  • Since we want to be asking the question repetitively we need to use a loop to achieve that &
  • Secondly, our question needs to be run at least once before we can check whether the user's answer is right or wrong and then decide to repeat the question or end the script - this is where the do...while stands out compared to the while loop

So then our solution to the problem using the do...while loop would look like this:

var answer = "JavaScript"; /* variable holds our expected answer */
var userResponse = "";  /* this variable would hold the user's response */
do{
  userResponse = prompt("What is the best programming language?");
}while(userResponse !== answer); 

Please note that you can also use the while loop to solve this problem though its structure does not naturally yield to these type of problems.

Hope this helps a bit.

Cheers!

Pratik Rai
Pratik Rai
6,856 Points

thank you andrew for this nice explanation.

You are welcome :)

Cheers!