Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Number.isNaN() return false for Strings?

Tags:

javascript

nan

As per my understanding NaN stands for Not A Number. Strings are not definitely Numbers and hence I expect the below code to return true for Strings. However, it's not the case.

console.log(Number.isNaN("Stack Overflow"));

Could somebody please clarify this?

like image 297
Beginner Avatar asked Jan 04 '23 18:01

Beginner


2 Answers

There is a distinction to be made between Number.isNaN and isNaN

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/isNaN

The isNaN() function determines whether a value is NaN or not.

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN

The Number.isNaN() method determines whether the passed value is NaN and its type is Number. It is a more robust version of the original, global isNaN().

The reason you are returning false is that "Stack Overflow" is not a number it is a string.

console.log('Number.isNaN("Stack Overflow"): '+Number.isNaN("Stack Overflow"));
console.log('isNaN("Stack Overflow"): '+isNaN("Stack Overflow"));
like image 131
Andrew Bone Avatar answered Jan 06 '23 13:01

Andrew Bone


https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Description

In comparison to the global isNaN() function, Number.isNaN() doesn't suffer the problem of forcefully converting the parameter to a number. This means it is now safe to pass values that would normally convert to NaN, but aren't actually the same value as NaN. This also means that only values of the type number, that are also NaN, return true.

like image 41
Ivan Sivak Avatar answered Jan 06 '23 12:01

Ivan Sivak