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

Ricky Redman
Ricky Redman
7,520 Points

do, while

The challenge keeps saying that my code is taking too long to run, any thoughts as to why I'm getting this error?

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!");

do {secret = prompt
   }   while (secret !== 'seasame');

2 Answers

Blake Larson
Blake Larson
13,014 Points

secret = prompt This line is not changing what is saved in secret. Prompt is a function so when you just use prompt as a variable it creates a infinite loop.

Ricky Redman
Ricky Redman
7,520 Points

Please elaborate further Blake. Still struggling with this concept

Blake Larson
Blake Larson
13,014 Points

Sure.

This line saves the user input to the variable named secret

   let secret = prompt("What is the secret password?");

Now what you want to do is call that prompt over and over until you guess the correct word (sesame). Each time you call the prompt function it will change the secret variable to whatever the user inputs.

A do while loop makes it so you can do something first before checking the conditional to break out of the loop. So what you can do is.

  let secret;

  do {
     secret = prompt("What is the secret password?");
   }   while (secret !== 'sesame');

So you set the secret value with prompt before checking if secret !== 'sesame'. A good way to think about do while loops is to say Do once, then while which is different then a while loop which just immediately checks a conditional value.

You then can put the alert at the end of the script because you don't want an alert before the loop is finished.