Skip to content
Advertisement

Parsing to Check if NAN Javascript

I have an onclick even set up to take the value of an input and alert if the value is a number. If the value of the input is blank, I am trying to alert it to say “No Number,” however, it seems that even if my input it empty the function returns a statement saying the the “empty” value is indeed a number.

I have set variable up to parse the value of the input right away, but is this why my code is always returning “Is a number,” because it’s automatically set to be one when it collects the variable?

Code:

HTML:

JavaScript

JS:

JavaScript

Advertisement

Answer

Checking if == NaN will always return false. The proper way to do this is with Number.isNaN():

JavaScript

You also had some issues with your logic in the if – each clause is a separate expression, and therefore needs to check against numberTest every time.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement