JS while loop problem

JS while loop problem
0

#1

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
}

#2

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

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

#3

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


#4

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");
}

#5

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


#6

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;
}

#7

thank you a lot, that was helpful


#8

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