While loop incorrect input


#1

Just playing around trying to create a while prompt loop where if the input is incorrect it loops back. The code works if the input is a number (correct or incorrect), however if the input is anything other than a number, the loop does not function. I would love an explanation as to why this is, also any help in fixing/solving the issue would be much appreciated!

var attack = Math.floor((Math.random()*10) + 1);

strength = 0;

while (strength === 0 || strength>10 || strength.typeof === 'string') {
    var strength = prompt("What is your strength?", "Type in a number between 1-10");
}


console.log("You used all your strength and managed to deal",attack*strength,"Damage");

#2

why not use a do while loop? a do while loop runs at least once (you want this, since you want user input) and then for as many times as needed until the user enters something valid.

Why not use isNaN? it is a build in function to check if the input is a number. if the input is a number, false is returned, otherwise true is returned, which is perfect, which means you get something like this:

do {
  var strength = prompt("What is your strength?", "Type in a number between 1-10");
} while (parseInt(strength) < 0 || parseInt(strength) > 10 || isNaN(strength))

let me explain this, i use isNaN to check the user gives me a number as input. i use parseInt to parse (cast) the input to a number, if you don't strength will be a string (even if the user enters a number) and comparing integers with strings is just weird


#3

Fantastic thank you! I was messing around trying to include isNaN but nothing was working. Really appreciate the help!


#4

Do you also understand everything? That is the most important bit


#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.