NaN
NaN
stands for Not a number- It represents a value which is not a valid number
- It's the one and only value which is not equals to itself
- Data Type of
NaN
is number NaN
is also one of the falsy values
_1console.log("abc" / 2); // returns NaN
This above line gives NaN
because /
is a numerical operator which expects
two numbers at both side, but since 'abc'
is not a number even though js tries
coercion.
Coercion
Coercion refers to converting from one dataType to another dataType. There are two types.
Implicit
Js itself tries to convert the datatype
_2var x1 = "7" - 6;_2// string "7" is converted implicitly by js due to "-" is a numerical operator
Explicit
The datatype is converted manually by us.
_2var x1 = Number("7") - 6;_2// Here "7" was converted to number with external factors
Check for NaN
There are two ways to check for NaN
isNaN()
Number.isNaN()
isNaN()
vs Number.isNaN()
isNaN()
Function converts the argument to a number and returns true if the value isNaN
Number.isNaN()
Function checks the argument type if its number and the value is equal toNaN
.
Behind the Scenes
Value(x) | isNaN(x) | Number.isNaN(x) |
---|---|---|
NaN | true | true |
undefined | true | false |
"42,0" | true | false |
{} | true | false |
[] | false | false |
'123' | false | false |
'123e' | true | false |
0 | false | false |
-0 | false | false |
"" | false | false |
" " | false | false |
parseInt('123e') | false | false |
isNaN()
_17// implementation 1_17function isNaN(x) {_17 let val = Number(x);_17 return val !== val;_17}_17_17// implementation 2_17const isNaN = (x) => Number(x) !== Number(x);_17_17console.log(isNaN(NaN)); // true_17// NaN is not a number so prints_17console.log(isNaN("123")); // false_17// "123" is converted to 123 which is not NaN_17console.log(isNaN(null)); // false_17// null is converted to 0 which is not NaN_17console.log(isNaN("abc")); // true_17// "abc" is converted to number which results in NaN
Number.IsNaN()
_10// implementation 1_10const NumberIsNaN = (x) => typeof x === "number" && x !== x;_10_10// implementation 2 - with isNaN_10const NumberIsNaN = (x) => typeof x === "number" && isNaN(x);_10_10console.log(NumberIsNaN(NaN)); // true_10// type of NaN is number and value is not a number_10console.log(NumberIsNaN("123")); // false_10// "123" is not number hence fails in the first condition itself
Conclusion
Number.IsNaN()
is better use if unnecessary coercion is not required
@ragavkumarv
swipe to next ➡️