JavaScript JavaScript Loops, Arrays and Objects Simplify Repetitive Tasks with Loops Create a `do...while` loop

Maima Kemokai
Maima Kemokai
1,928 Points

Re-write the code to use a do...while loop. Stuck on this for about two day now can anyone help

Re-write the code to use a do...while loop.

Can anyone help

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


do {
secret = prompt("what is the secret password?");
  wordCount += 1;
  if(parseInt(word) ===randomWord {
     correctWord = true;
}
{while(! correctWord) 
 {document.write ("You know the secret password. Welcome."):
 document.write ('<h1> you guessed the word!</h1>');
 }
index.html
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JavaScript Loops</title>
</head>
<body>
<script src="script.js"></script>
</body>
</html>

2 Answers

Devin Thomas
Devin Thomas
2,921 Points

Try this approach.

var secret;
do{
  secret = prompt("What is the secret password?");    
}
while ( secret !== "sesame" ) 
document.write("You know the secret password. Welcome.");
Antonio De Rose
Antonio De Rose
20,840 Points
// Normal while 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.");

// Let us now turn this to be a do while loop

// step 1 => let us bring the boiler plate

do {

}
while ( )

// step 2 => let us translate the while loop code into do while, expect for trial and error
// you may not get the first time

var secret = prompt("What is the secret password?") // now the prompt will have to go inside the do, for the while to do 
the remaining, value of secret, in while is checked, that said, value of secret should be tried in do, for the do while to operate

// step 4  => for that reason, we will only declare the variable above the do while like below

var secret;

do {
var secret = prompt("What is the secret password?");
// step 5 => once declared at step step 4, we cannot declare again, take the var out. and make it look like below
secret = prompt("What is the secret password?");
}
while ( secret !== "sesame" ) // step 3 => this step easy, same as while loop, copy and paste, only location of the while changed