Blog

NaN

JS

isNan() vs Number.isNaN()

Which is better to use isNan() or Number.isNaN()?

Karthick V

Karthick V

Sep 27, 2022 — Updated Dec 8, 2022 · 2 min read

  1. NaN stands for Not a number
  2. It represents a value which is not a valid number
  3. It's the one and only value which is not equals to itself
  4. Data Type of NaN is number
  5. NaN is also one of the falsy values

_1
console.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 refers to converting from one dataType to another dataType. There are two types.

Js itself tries to convert the datatype


_2
var x1 = "7" - 6;
_2
// string "7" is converted implicitly by js due to "-" is a numerical operator

The datatype is converted manually by us.


_2
var x1 = Number("7") - 6;
_2
// Here "7" was converted to number with external factors

There are two ways to check for NaN

  1. isNaN()
  2. Number.isNaN()
  1. isNaN()
    Function converts the argument to a number and returns true if the value is NaN
  2. Number.isNaN()
    Function checks the argument type if its number and the value is equal to NaN.
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

_17
// implementation 1
_17
function isNaN(x) {
_17
let val = Number(x);
_17
return val !== val;
_17
}
_17
_17
// implementation 2
_17
const isNaN = (x) => Number(x) !== Number(x);
_17
_17
console.log(isNaN(NaN)); // true
_17
// NaN is not a number so prints
_17
console.log(isNaN("123")); // false
_17
// "123" is converted to 123 which is not NaN
_17
console.log(isNaN(null)); // false
_17
// null is converted to 0 which is not NaN
_17
console.log(isNaN("abc")); // true
_17
// "abc" is converted to number which results in NaN


_10
// implementation 1
_10
const NumberIsNaN = (x) => typeof x === "number" && x !== x;
_10
_10
// implementation 2 - with isNaN
_10
const NumberIsNaN = (x) => typeof x === "number" && isNaN(x);
_10
_10
console.log(NumberIsNaN(NaN)); // true
_10
// type of NaN is number and value is not a number
_10
console.log(NumberIsNaN("123")); // false
_10
// "123" is not number hence fails in the first condition itself

Number.IsNaN() is better use if unnecessary coercion is not required

@ragavkumarv
swipe to next ➡️