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

not sure where to start, feel confused

script.js
// Display the prompt dialogue while the value assigned to `secret` is not equal to "sesame"
let secret = prompt("What is the secret password?");

// This should run after the loop is done executing
alert("You know the secret password. Welcome!");




let secret;
do {
  // code to run
}
while ( password !== 'abc123' );

1 Answer

Dane Parchment
MOD
Dane Parchment
Treehouse Moderator 11,077 Points

Alright. So basically a do..while loop is a while loop, that always runs once.

So was we know a while loop, will always run until it's loop condition is satisfied, however, it may not always run if the condition is already met. Sometimes, we want the body of the loop to always run at least one, a do...while loop allows us to do this.

How? Well here's the syntax

do {
  // whatever you needed to do inside the loop
} while(condition is not met);

In our specific case we need to make sure that the prompt is always run at least once so let's re-write and re-arrange the code a little by converting this:

// Display the prompt dialogue while the value assigned to `secret` is not equal to "sesame"
let secret = prompt("What is the secret password?");

// This should run after the loop is done executing
alert("You know the secret password. Welcome!");

to this:

// Display the prompt dialogue while the value assigned to `secret` is not equal to "sesame"
let secret = '';
do {
  secret = prompt("What is the secret password?");
} while(secret !== 'sesame');

// This should run after the loop is done executing
alert("You know the secret password. Welcome!");

This is how we would accomplish the task. However, instead of just copy pasting this code, I recommend you go back and watch previous videos again to get a better grasp of the subject before moving on. That way you properly learn the content!

Dane Parchment this is the best answer I ever received for any question, thank you so much. was watching videos on it, and this also helped me too.