Identify and Deal with NaN in JavaScript

Marius Schulz
InstructorMarius Schulz

Share this video with your friends

Send Tweet
Published 5 years ago
Updated 3 years ago

Dealing with the special NaN value can be tricky in JavaScript. It behaves like a number and not a number at the same time. This lesson explains how to identify it using the isNaN function or the Number.isNaN method.

[00:00] JavaScript defines a special value called NaN, which stands for Not-a-Number. This value is produced whenever an arithmetic operation results in an undefined or unrepresentable value. For example, if you divide zero by zero, or if you try to convert the string JavaScript to a number.

[00:18] NaN is a falsy value. That is, converting NaN to a Boolean value will yield false. Therefore, if NaN is the left operant of the logical OR operator, the resulting value will be the right operant. Perhaps confusingly, the type of NaN is number, although its name says Not-a-Number.

[00:37] Another peculiarity of NaN is that it's not considered to be equal to itself, neither by double equals, nor by triple equals. In fact, it is the only value in JavaScript that behaves this way. Because a regular equality check returns false, we need another special mechanism to detect the NaN value.

[00:56] One such mechanism is the global isNaN function. If you pass NaN to it, it returns true. The problem with the isNaN function is that it returns true for other values, as well, leading to false positives. Internally, isNaN converts the given value to a number.

[01:11] As we've seen before, converting the string JavaScript to a number produces the NaN value. Therefore, the isNaN function returns true in this case. This is probably not what you intended. Some strings can be converted to numbers, though.

[01:26] For instance, the empty string becomes zero. In that case, isNaN returns false. I recommend you avoid using the global isNaN function to steer clear of these pitfalls. Luckily, there is a reliable mechanism to detect NaN, and that's the isNaN method found on the number object.

[01:45] Notice that the Number.isNaN method is different from the global isNaN function. Number.isNaN only returns true if given the actual NaN value, and in all other cases, it returns false. This is much more likely what you expected.

[01:59] Finally, here's a simple polyfill to make Number.isNaN work in older browsers, as well. The fallback function makes use of the fact that NaN is the only value in JavaScript that is not considered to be equal to itself.