Why is the result of Number.isNaN('abc') false?

Viewed 311

I've looked at the MDN Documentation and other Stack Overflow questions, however was not able to find an exact reasoning for this one. I understand that isNaN tries to parse the values into number, but when I try to run Number.parseInt or Number.parseFloat on 'abc' it gives me 'NaN' but when I actually run the isNaN function it gives me 'false'.

I am aware that there are better ways to check if something is a number or not such as Number.isFinite( ), but in this case I am trying to understand how isNaN is working.

console.log(Number.parseInt('abc'));
console.log(Number.parseFloat('abc'));

console.log(Number.isNaN('abc'));

2 Answers

NaN is a special number value. Number.isNaN verifies whether the passed in value is equal to NaN, because "normal" comparison doesn't work (NaN == NaN is false by definition).

Unlike some other methods, Number.isNaN does not perform type conversion. 'abc' is a string value therefore it cannot be NaN.

The specification defines Number.isNaN as:

  1. If Type(number) is not Number, return false.
  2. If number is NaN, return true.
  3. Otherwise, return false.

Note that there's also the global isNaN function, which behaves differently: If you give it a value that isn't of the number type, it converts it to the number type before doing its check. So isNaN('abc') is true because if you convert 'abc' to number using the default string-to-number conversion, you get NaN; but Number.isNaN('abc') is false because it doesn't do that conversion.

Not adding anything new here.

Simply trying to make it a bit more clear for beginners.


isNaN(value) checks if value is literally "NaN".

If value is "NaN", isNaN(value) returns true.

If value is anything else (eg. number, or string, or undefined, or null, or Infinity, or anything else, isNaN(value) returns false.

//Examples that Return FALSE
//
console.log(20); // value is 20 - is NOT NaN
console.log(isNaN(20)); // false   

console.log('20'); // value is "20" - is NOT NaN
console.log(isNaN('20')); // false


console.log(23 / 0); // is Infinity - Is NOT NaN
console.log(isNaN(23 / 0)); // false


//Examples that Return TRUE
//

console.log(parseInt('X20')); // is NaN
console.log(isNaN(parseInt('X20'))); // true 

console.log(+'20X'); // is NaN
console.log(isNaN(+'20X')); // true 

console.log(Math.sqrt(-1)); // is NaN
console.log(isNaN(Math.sqrt(-1))); // true 

console.log(7 ** NaN); // is NaN
console.log(isNaN(7 ** NaN)); // true 

console.log(0 * Infinity); // is NaN
console.log(isNaN(0 * Infinity)); // true 

console.log('foo' / 30); // is NaN
console.log(isNaN('foo' / 30)); // true `

As correctly noted, it's better to use Number.isFinite(value) to check if value is a number.

Related