skip to Main Content

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:

  1. Why there is a difference between (guess-0) and guess-0?
  2. Why in console guess-0 gives NaN but stript gives me It is number anyway?
  3. 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


  1. typeof has higher precedence than arithmetic operators. So

    typeof guess - 0
    

    is evaluated as if you’d written

    (typeof guess) - 0
    

    which is equivalent to

    "string" - 0
    

    and the value of this is NaN.

    But when you write

    typeof (guess-0)
    

    it’s equivalent to

    typeof NaN
    

    Since NaN is a number type (despite being an abbreviation for "not a number"), this returns "number".

    Login or Signup to reply.
    1. Why there is a difference between (guess-0) and guess-0?

    The former equates to typeof (guess - 0). Ineerting the values turns this in to 't5' - 0 which becomes NaN due to the fact that you cannot coerce the string 't5' in to a Number. Finally typeof NaN returns Number.

    The latter (effectively) becomes to (typeof guess) - 0. So the typeof 't5' operation is performed first, resulting in string. Then you attempt 'string' - 0, which returns NaN.

    1. Why in console guess - 0 gives NaN but stript gives me ‘It is number’ output anyway?

    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 your if condition is failing and the logic always flows to ‘It is a number’.

    1. Is is really that complicated to just check if input is a number?

    No, you just need to use the isNaN() function instead of comparing the output to a string.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search