What is NaN?

NaN, in JavaScript, can be many things. In fact, it can be almost anything, so long as it is Not a Number. Its type is technically “number” (when evaluated with “typeof”), although it stands for Not a Number.

What causes values to become NaN?

Values can become NaN through a variety of means, which usually involve erroneous math calculations (such as 0/0), or as a result of type coercion, either implicit or explicit. A common example is when you run parseInt on a string that starts with an alphabetical character. This isn’t exclusive to parseInt, as it also applies when using explicit coercion with Number(), or with the unary “+” operator.

How do you check for NaN?

Before selecting a method for checking for NaN, how should you not check for NaN?

NaN is a bizarre value in JavaScript, as it does not equal itself when compared, either with the loose equality (==) or strict equality (===) operator. NaN is the only value in the entire language which behaves in this manner with regards to comparisons.

For example, if parseInt(“a”) returns NaN, then parseInt(“a”) === NaN will return false. This may seem strange, but it makes perfect sense after thinking about what NaN really is.

NaN doesn’t tell you what something is, it tells you what it isn’t.

These two different strings being passed to parseInt() will both return NaN.

parseInt(“abc”) // NaN
parseInt(“def”) // NaN

#javascript #nan #programming

Checking for NaN in JavaScript
1.10 GEEK