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

Confusing loop results

The challenge asks you to turn this while loop into a do while loop. My question is about both types of loop.

var secret = prompt("What is the secret password?"); while ( secret !== "sesame" ) { secret = prompt("What is the secret password?");
} document.write("You know the secret password. Welcome.");

What confuses me about this loop is that when I enter a word that is not "sesame" it loops twice and then displays the document.write string anyway. I can't figure out why the while loop is breaking and running the document.write().

Then when I change it to a do...while loop like this (which passed the challenge)

var secret; do { secret = prompt("What is the secret password?"); } while ( secret !== "sesame" ) document.write("You know the secret password. Welcome.");

The document.write string is displayed no matter what I enter in the prompt.

Am I missing something after the while ( secret !== "sesame" ) statement that would actually make the loop keep running until "sesame" is entered?

1 Answer

Steven Parker
Steven Parker
231,275 Points

I tried both versions, and they seem to work correctly. Both of them keep asking for input as long as I answer with something other than "sesame". And when I give "sesame", they both end and display the message.

Perhaps try it with a different browser?