What Is NaN in JavaScript?

JavaScript NaN Explained

In JavaScript, NaN is a special numeric value:

typeof NaN; // 'number'

Please note that NaN (property of the global object) and Number.NaN (property of the Number object) are equivalent.

It represents "Not-a-Number" (as defined in the IEEE-754 standard). NaN never equals to any other number, or even to itself:

NaN === NaN; // false

Therefore, to check if a number is NaN or not, you would use the Number.isNaN() method (or the slightly different isNaN() global function). However, do not confuse these as a means to check whether a non-numeric value is a number or not. For that, you should instead use:

typeof value === 'number'; // true/false

NaN is actually, rarely used in a program. Typically, it is returned from a function or operation to indicate a failed operation on numbers, suggesting that the value is not a legal number (where you may be expecting the return value to be a legal number). Such is the case, for example, when:

Parsing Numbers

NaN is returned when a value cannot be parsed into a number. For example:

parseInt('foo'); // NaN
Number('foo'); // NaN

parseInt(undefined); // NaN
Number(undefined); // NaN
// ...

Using NaN as an Operand

When an expression has NaN, the resulting value is NaN. Consider, for example, the following:

3 + NaN; // NaN
3 * NaN; // NaN
3 / NaN; // NaN
// ...

Using undefined as an Operand

When undefined is used as an operand, the resulting value is NaN. Consider, for example, the following:

3 + undefined; // NaN
3 * undefined; // NaN
3 / undefined; // NaN
// ...

Using Indeterminate Form

When an operation is in indeterminate form, it returns NaN. For example:

undefined + Infinity; // NaN
undefined + undefined; // NaN

0 * Infinity; // NaN
0 * undefined; // NaN
// ...

Math Operation That Does Not Result in a Real Number

A math operation that does not yield a real number, such as when a mathematical function receives an invalid argument, NaN is returned. For example:

Math.sqrt(-1); // NaN
// ...

Performing Non-Addition Operation on a String

Using a operations other than addition on a string yields NaN. For example:

'foo' + 3; // 'foo3'

'foo' - 3; // NaN
'foo' / 3; // NaN
'foo' * 3; // NaN
// ...

Hope you found this post useful. It was published . Please show your love and support by sharing this post.