what is NaN?
The NaN property in the global object represents "Not a Number" value.This property indicates that a value is an invalid number.NaN is the return value from operations which have an undefined numerical result.
- NaNs are part of IEEE 754 spec, which is a numerical representation specification. so, the type of a NaN is number.
NaN === NaN //false typeof NaN //number
NaN with any mathematical operation is always NaN.
10 - "Maguire" //NaN
In the above code, the string is coerced to a number which is invalid(NaN). so, it returns NaN.
isNaN(5) //false isNaN("Tobey") //true
When we pass a number, it returns false and true for NaN.
But, "Tobey" is not NaN, its a string. The isNaN() utility coerces the value to numbers before it checks. so, the string "Tobey" is coerced to numbers. which is an invalid number(NaN). so, it outputs true. It was considered a bad idea. so, a new utility was introduced in ES6.
It doesn't do any coercion. And it outputs true if the passed value is NaN and its type is Number.
const returnString = () => 'Bully Maguire' const returnNaN = () => NaN //isNaN isNaN(returnString()) ? true : false //true isNaN(returnNaN()) ? true : false //true //Number.isNaN Number.isNaN(returnString()) ? true : false //false Number.isNaN(returnNaN()) ? true : false //true
The above example tells the difference between isNaN and Number.isNaN.
And I hope you learned something useful. Thanks a lot 🙏