Home > Net >  How to escape a prompt with while loop with isNaN in JavaScript?
How to escape a prompt with while loop with isNaN in JavaScript?

Time:10-08

So my while loop with isNaN doesn't work when I type in number in the prompt Here is my code below...

var userSalary = prompt("Please type your salary!")

while(isNaN(userSalary)){
    prompt("Please type number!")
}
alert("Good!") 

Although I input a number, it won't let me escape from the loop...

CodePudding user response:

You need to reassign userSalary inside of the loop, so the value gets refreshed:

var userSalary = prompt("Please type your salary!")

while(isNaN(userSalary)){
    userSalary = prompt("Please type number!")
}
alert("Good!")

CodePudding user response:

You could combine the statements, and also try a do..while loop

var userSalary = prompt('Please type your salary!')
while (isNaN(userSalary = prompt('Please type number!'))) {}
alert('Good!')

CodePudding user response:

var userSalary;
function checkS(){
      userSalary = prompt("Please type your salary!");
      if(isNaN(userSalary)){
         checkS();
         return;
      }
      alert('Good');
}
checkS();

  • Related