Do...while loop question?

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

This is a do…while loop that asks the user the question “What is the secret password?”. The loop will keep running until they give the answer “sesame” and at that point the condition runs false causing the loop to end. afterwords the message “You know the secret password. Welcome” appears. My question is how does the computer know to document.write(“You know the secret password. Welcome.”); after the loop ends when it is not wrapped around curly braces?

Hi @paine8887

The curly braces { } are wrapped around the code which is executed during every iteration of the do…while loop.

Once the loop exits, it will continue to the next line of the program and so we get “You know the secret password. Welcome.” written to the console.

If this line were inside the braces, it would be written to the console every time the loop ran which is not what we want. :grin:

1 Like