+ 2

Why cant I catch invalid input in this code?

Why this code doesn't catch invalid input like "&, *, (, p, ]" with "while (!guess)"? let guess= window.prompt('guess the number!'); const rand=Math.floor(Math.random()*10)+1; let tries= 0; while (!guess){ let guess=parseInt(prompt('enter a valid number')); } while (parseInt(guess)!==rand){ tries+=1; if (guess==='q'){ console.log('you have exited'); break; } if (guess<rand) guess=prompt('enter higher!'); else (guess>rand) guess=prompt('enter lower!'); } console.log(`correct number is : ${rand} and it took you ${tries} tries`);

13th Apr 2021, 12:44 AM
LIGHT
LIGHT - avatar
1 Answer
+ 2
If the first value you enter into prompt is "&", that won't be equated with true. If you enter an empty string in the first prompt, you'll get into the while-loop that you want. The while-loop won't work the way you want because it isn't written very well. let game =... declares another variable with the same name in a scope that you don't want. The scope of that while-loop game variable is between the { } brackets of the loop so the while-loop condition will always be true. The following will work more the way you want: function getGuessedNumber(msg) { let guess= prompt(msg); if (guess === 'q') return guess; guess = parseInt(guess); while (isNaN(guess)){ guess=prompt('enter a valid number'); if (guess === 'q') return guess; else guess = parseInt(guess); } return guess; } const rand=Math.floor(Math.random()*10)+1; let tries= 0; let guess = getGuessedNumber('guess the number!'); while (guess !== rand){ tries+=1; if (guess==='q'){ console.log('you have exited'); break; } if (guess<rand) guess=getGuessedNumber('enter higher!'); else if (guess>rand) guess=getGuessedNumber('enter lower!'); } console.log(`correct number is : ${rand} and it took you ${tries} tries`);
13th Apr 2021, 12:52 PM
Josh Greig
Josh Greig - avatar