JS while loop problem

Hello guys.
I want to get input using prompt until the one specific word is not entered. How to do that correctly?

var word = "dog";
var string1 = prompt("Enter a word");
if (string1 !== word) {
   string1 = prompt("Enter again"); // how to prompt as many times until the "dog" is not entered
}

Use a do...while loop. See below:

var word = "dog";
do{
  var string1 = prompt("Enter a word");
}while(string1 !== word)

Okay, that works, thanks. But isn’t there any way to solve the problem only with while loop?

Yes, its the same logic. I only used a do..while since it will always run once before checking the condition. I felt that the do...while was a more concise solution. See below:

var word = "dog";
var string1 = prompt("Enter a word");
while(string1 !== word){
  string1 = prompt("Try again");
}
1 Like

If I add new variable and check for that too. In that case I must write:

var word = "dog";
var word1 = "cat";
var string1 = prompt("Enter a word");
while ( (string1 !== word) || (string1 !== word1) ){
  string1 = prompt("Try again");
}

But this doesn’t work. Even if I type dog or cat the program continues to prompts saying Try again. What’s the problem?

Thanks

The problem with your logic here is that the while loop will run as long as the condition in the parentheses is true. So if you type in ‘dog’, the first condition evaluates to false while the second will evaluate to true. In other words, this loop will always run. Think about it, one of those conditions will always be true. See below for a way to solve this

var word = "dog";
var word1 = "cat";
var string1 = prompt("Enter a word");
var check = string1 == word || string1 == word1;
while (!check) {
  string1 = prompt("Try again");
  check = string1 == word || string1 == word1;
}
3 Likes

thank you a lot, that was helpful

1 Like

I cleaned up your code.
You need to use triple backticks to post code to the forum.
See this post for details.

1 Like