title: JavaScript Prompt Validation for Integer Input
body: <p>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 <code>cancel</code> returns <code>null.</code></p>
  
  <p>What I originally tried (ported from a Python program) was:</p>
  
  <pre><code>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;
  }
  </code></pre>
  
  <p>However, this returns <code>NaN</code> if I cancel the prompt, which doesn't make sense as a return value (it seems <code>isNaN(null)</code>returns <code>false</code>). (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").</p>
  
  <p>So after some thought, I came up with:</p>
  
  <pre><code>function getInteger(){
      while(true){
          let input = prompt("Input number: ");
          if (input &amp;&amp; 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()
  </code></pre>
  
  <p>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 <code>while(true)</code> considered a bad idea?</p>
  
  <p>I'm aware that prompts in general are probably a bad idea, but that's not the point here.</p>
  
  <p>Any help appreciated.</p>