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?
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"));
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With