I found myself needing to create a function to validate the input of a JS prompt as an integer. It turns out there is a little subtlety involved as pressing cancel returns null.
What I originally tried (ported from a Python program) was:
function getInteger() {
let number = null
while ( number == null ) {
let value = prompt( "Guess number: " )
if ( isNaN( value ) ) {
alert( "Invalid input." )
} else {
number = parseInt( value )
}
}
return number;
}
However, this returns NaN if I cancel the prompt, which doesn't make sense as a return value (it seems isNaN(null)returns false). (By doesn't make sense, I mean "can't be meaningfully used by the rest of the program as it's not descriptive of what happened").
So after some thought, I came up with:
function getInteger(){
while(true){
let input = prompt("Input number: ");
if (input && isNaN( input ) ) {
// user pressed OK, but input invalid
alert("Invalid input.");
} else if (input) {
// user typed something valid and hit OK
return parseInt(input);
} else {
// User pressed cancel
alert("I'm out of here.")
return;
}
}
}
getInteger()
I'm curious as to whether I've covered all possible inputs? Also, whether my code is "well written" - is there a better way to do it? Is using while(true) considered a bad idea?
I'm aware that prompts in general are probably a bad idea, but that's not the point here.
Any help appreciated.