0

I need to check a value is a number. I have two solutions:

typeof input !== 'number'

and

isNaN(input)

What is the difference. Who choose one over the other?

seventeen
  • 557
  • 1
  • 6
  • 21
  • 4
    `isNaN` which stands for `is Not a Number` does actually _not_ check whether the value passed is not of type `number`, it checks for the special value `NaN`. – tkausl Apr 20 '21 at 23:37
  • isNaN('a') is true isNaN(1) is false So it looks to me like it tries to turn 'a' into a number, if it cant it becomes NaN. – seventeen Apr 20 '21 at 23:41
  • 1
    `typeof NaN === "number"` btw – SuperStormer Apr 20 '21 at 23:41
  • 1
    Number as in digit or number as in type? You've provided two different functions with two different meanings here. – Nora Apr 20 '21 at 23:43
  • I now see. A string containing a number is false if isNaN is used. Yet with type of matches the type as well. – seventeen Apr 20 '21 at 23:45
  • Thanks that helps. – seventeen Apr 20 '21 at 23:49
  • `Number.isNaN` checks for `NaN`, the global `isNaN` checks, whether the value converted to number is `NaN`, which can often be [surprising](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN#confusing_special-case_behavior). – ASDFGerte Apr 20 '21 at 23:49

0 Answers0