testing for NaN

NaN, Not a Number, is returned when doing math operations with values that aren’t numbers.

NaN’s type is a number.

JavaScript

const division = 1 / 'e';

console.log(division); // NaN
console.log(typeof division); // number

When comparing NaN to itself it will always evaluate to false.

JavaScript

const division = 1 / 'e';

console.log(division === NaN); // false
console.log(division == NaN); // false

This could be used as a way to check if a value is NaN.

Number.isNaN() could also be used to check if a value is NaN.

JavaScript

const division = 1 / 'e';
const string = 'hi';

console.log(Number.isNaN(division)); // true
console.log(Number.isNaN(string)); // false

summary

When checking if a value is NaN use Number.isNaN().

javascript
changing the type of a value - coercion in javascript

Using a value in a comparison can be confusing sometimes because JavaScript tries to be helpful and implicitly change the type for you.

javascript
using JSON.stringify() with values that are not JSON safe

Some JavaScript values are not JSON safe