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

do...while loop, Evaluate to False ... Correct Answer, but there's a bug?

SOURCE: https://teamtreehouse.com/library/javascript-loops/simplify-repetitive-tasks-with-loops/create-a-dowhile-loop

This is the solution that passed the test:

// Display the prompt dialogue while the value assigned to `secret` is not equal to "sesame"

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

do {
    secret = prompt(`That's not it! Try again ... 
    What is the secret password?`);

} while ( secret !== "sesame");
alert("You know the secret password. Welcome!");

What happens is:

  1. The prompt dialogue box pops up for you to enter the password.
  2. Enter an incorrect password, and the do...while loop causes the prompt to reappear, with the additional message "That's not it! Try again ..."

The problem occurs when a use enters the CORRECT answer on the first attempt. The code inside the do...while loop runs once, which is normal, but it runs the password prompt, which it shouldn't do, because the user has already submitted the correct answer.

Shouldn't this task have been a while loop, rather than a do...while?

This appeared to work better:

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

while (secret !== "sesame") {
    secret = prompt(`That's not it! Try again ... 
    What is the secret password?`);
}
alert("You know the secret password. Welcome!");
console.log("You know the secret password. Welcome!");

1 Answer

Steven Parker
Steven Parker
231,248 Points

You're getting a bit fancy, the challenge wasn't asking you to create a separate prompt for a bad attempt. It was only asking you to ask the (one) question inside a "do" loop repeatedly until the answer is correct.

But your approach would certainly create a better user experience in a real-life situation.   :+1: