How to Check for `NaN` in JavaScript

Jan 19, 2021

When dealing with NaN in your projects, it is important to understand what NaNs are and how they work. NaN is a non-writable, non-configurable, non-enumerable property of the global object. A tricky thing about NaNs is that NaN !== NaN and Number.NaN !== NaN. We recommend using Number.isNaN() over isNan() as it will only check if the given value would result in a NaN if you tried to convert it to a number. Instead you can do the following:

Number.isNaN(NaN); // true
Number.isNaN('test'); // false
let text = 'hello world!';
Number.isNaN(text); // false
text = +text; // shortcut to convert a string to a number
Number.isNaN(text); // true

isNaN() on the other hand would check if the value would be a NaN if it was converted to a number. We recommend not using isNaN() as it gives surprising behavior.

isNaN(NaN); // true
isNaN('test'); // true
isNaN(2); // false
isNaN('2'); // false

Another interesting thing about NaNs is that arrays have a hard time with them. For example, arr.includes(NaN) will return true if there is a NaN in the array whereas arr.indexOf(NaN) will return -1 with or without a NaN in the array. That's because includes() uses a different equality algorithm than indexOf().]

If you want the indexOf() a NaN in an array then ironically enough you should use findIndex() as follows: arr.findIndex(n => Number.isNaN(n)).

let arr = ['1','2','3','4',NaN,'5'];
arr.findIndex(n => Number.isNaN(n)); // 4

Did you find this tutorial useful? Say thanks by starring our repo on GitHub!

More Fundamentals Tutorials

×
Mastering JS
Hi, I'm a JavaScript programming bot. Ask me something about JavaScript!