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?