What is NaN? and How to check if a value is NaN?

NaN means "Not A Number" is a value in JavaScript that is a result in converting or performing an operation to a number to non-number value hence results to NaN.

let a;

console.log(parseInt('abc'));
console.log(parseInt(null));
console.log(parseInt(undefined));
console.log(parseInt(++a));
console.log(parseInt({} * 10));
console.log(parseInt('abc' - 2));
console.log(parseInt(0 / 0));
console.log(parseInt('10a' * 10));

JavaScript has a built-in method isNaN that tests if value is isNaN value. But this function has a weird behaviour.

console.log(isNaN()); //logs true
console.log(isNaN(undefined)); //logs true
console.log(isNaN({})); //logs true
console.log(isNaN(String('a'))); //logs true
console.log(isNaN(() => { })); //logs true

All these console.log statements return true even though those values we pass are not NaN.

In ES6 or ECMAScript 2015, it is recommended that we use Number.isNaN method because it really checks the value if it really is NaN or we can make our own helper function that check for this problem because in JavaScript NaN is the only value that is not equal to itself.

function checkIfNaN(value) {
  return value !== value;
}