The value NaN
stands for not a number**, yet in JS, it belongs to the number
type.
console.info(typeof NaN) // number
It usually arises from attempting to convert a non-numeric value to a number.
To check if a variable holds NaN
, two functions can be used:
window.isNaN()
takes one argument, converts it to a number, then checks if it equals NaN
. It can lead to unexpected results as some values, when converted to a number, behave differently.
console.info(Number(NaN), isNaN(NaN)); // NaN, true console.info(Number(true), isNaN(true)); // 1, false console.info(Number(false), isNaN(false)); // 0, false console.info(Number("string"), isNaN("string")); // NaN, true console.info(Number({}), isNaN({})); // NaN, true console.info(Number([]), isNaN([])); // 0, false
The Number.isNaN()
function takes one argument and checks if it is equal to NaN
. It does not convert to a number.
console.info(Number.isNaN(NaN)); // true console.info(Number.isNaN(true)); // false console.info(Number.isNaN(false)); // false console.info(Number.isNaN("string")); // false console.info(Number.isNaN({})); // false console.info(Number.isNaN([])); // false