user16765028
user16765028

Reputation:

Keep showing prompt, until correct value is given in javascript

I am trying to show the prompt everytime, the user gives a null or incorrect input. Only upon, giving the correct entry, will the prompt go and an alert will be shown. This is my code:

var pass=prompt("Please enter the password to view your recovery code.");
while(true){
    if(pass=="abc"){
        break;
    }
    else
       var pass=prompt("Please enter the password to view your recovery code."); 
}

alert("correct");

Now, even if I give the correct value (abc), the prompt still remains and the alert never shows. Why?

Upvotes: 0

Views: 1131

Answers (2)

RenaudC5
RenaudC5

Reputation: 3829

The error was because you had re-define the variable pass with the line var pass=prompt(...)

You should also consider using let instead of var

Also, i've updated the condition do make something a little bit cleaner

let pass = prompt("Please enter the password to view your recovery code.");
while(pass !== "abc"){
       pass = prompt("Please enter the password to view your recovery code."); 
}

alert("correct");

Upvotes: 2

Andy
Andy

Reputation: 63524

It can be simpler than that. Add the prompt inside the loop, and break if the password is a match.

while (true) {

  const pass = prompt('Please enter the password to view your recovery code.');
  
  if (pass === 'abc') {
    console.log('Correct!');
    break;
  }

}

Upvotes: 2

Related Questions