This blog post is all about NaN & isNaN in javaScript.
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.
Interesting facts about NaN
- NaN is the only thing in javascript that is not equal to itself. Because IEEE declared NaNs are not equal to each other.
- 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.
utilities which determine if the value is NaN:
- isNaN()
- Number.isNaN()
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.
A better utility: π€
- Number.isNaN()
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 π
Top comments (1)
Interesting π€