1

I'm a beginner to JavaScript so I may have overlooked something here, so please bear with me.

I'm playing around with the parseInt() function, and wrote the following inline script:

var userInput = parseInt(prompt("Provide a number.", ""),10)

if (typeof(userInput) == 'number') {
   console.log("The user supplied a number")
} else if (typeof(userInput) == NaN) {
  console.log("The user did not supply a number")
}

The expected behaviour is that that when I supply a number "The user supplied a number" would be logged to the console, and alternatively when I supply anything else "The user did not supply a number" would be logged. However this is not the case, and it seems that "The user supplied a number" is always triggered.

I attempted to investigate why this was by checking the type values of string and number inputs to parseInt():

typeof(parseInt(1))
// "number"

typeof(parseInt("string"))
// "number"

So it seems that the typeof function evaluates any value from parseInt() as a number, which is at odds with the values parseInt() returns itself:

parseInt("1")
// 1

parseInt("string")
// NaN

Why is this? Additionally, how can I better evaluate user input in the context of my example?

seeker
  • 530
  • 1
  • 4
  • 14
  • 3
    Because `parseInt` always returns a number. If the value can't be parsed to a number, `NaN` is returned, and type of `NaN` is number. – Teemu Mar 10 '20 at 06:03
  • 2
    The fact you are likely lacking is `typeof NaN == 'number'`. Also with regard to your second `if` statement: The result of `typeof` is always a string, so comparing with the special value `NaN` will never evaluate to true. – Sirko Mar 10 '20 at 06:03
  • 3
    `typeof NaN ` is also a number. Use `isNaN(userInput)` to check whether something is `NaN` or not. – Maheer Ali Mar 10 '20 at 06:04

0 Answers0