I tried my best to figure it out on my own…
Just started learning JS (had some experience with Java earlier) and I try to mess around with a code a little while doing Jonas Schmedtmann’s Udemy course. Here goes my confusion.
There is a simple HTML page with <input type="text" class="guess" />
where user should put a number but I intentionally changed type to text to make JS do the input validation. I wrote this:
const guess = document.querySelector('.guess').value;
debugger;
if (guess - 0 === "NaN") console.log('Not a number');
else console.log('It is number');
As a result, there is always It is number
for whatever reason. Console debugging after ‘t5’ typed in:
> guess
't5'
> typeof guess
'string'
> guess-0
NaN
> typeof guess-0
NaN
> typeof (guess-0)
'number'
Questions:
- Why there is a difference between
(guess-0)
andguess-0
? - Why in console
guess-0
givesNaN
but stript gives meIt is number
anyway? - Is is really that complicated to just check if input is a number? I knew not defining variable class will be mess but I didn’t expect to hit me this early. What is a best/simpliest way to do validation like that?
2
Answers
typeof
has higher precedence than arithmetic operators. Sois evaluated as if you’d written
which is equivalent to
and the value of this is
NaN
.But when you write
it’s equivalent to
Since
NaN
is a number type (despite being an abbreviation for "not a number"), this returns"number"
.The former equates to
typeof (guess - 0)
. Ineerting the values turns this in to't5' - 0
which becomesNaN
due to the fact that you cannot coerce the string't5'
in to a Number. Finallytypeof NaN
returnsNumber
.The latter (effectively) becomes to
(typeof guess) - 0
. So thetypeof 't5'
operation is performed first, resulting instring
. Then you attempt'string' - 0
, which returnsNaN
.In JS
NaN
is a value representing a value that is Not a Number. It is not equal to the string'NaN'
, which is why yourif
condition is failing and the logic always flows to ‘It is a number’.No, you just need to use the
isNaN()
function instead of comparing the output to a string.