Understanding JavaScript NaN

This article is a complementary resource to the Learn JavaScript Basics course.

Understanding JavaScript NaN

In JavaScript, NaN ("Not a Number") is the result of invalid mathematical operations.

Example: Multiplying $25 and $25

let result = "$25" * "$25";
console.log(result);

Output

NaN

Here, JavaScript attempts to convert the strings $25 and $25 into numbers. However, the $ symbol makes the conversion invalid, so the multiplication operation results in NaN.


Common Scenarios Where NaN Occurs

1. Invalid String Conversion

NaN occurs when JavaScript tries to convert a non-numeric string to a number:

let num = parseInt("abc123");
console.log(num); // Output: NaN

2. Math Errors

Certain mathematical operations inherently result in NaN:

let result = 0 / 0;
console.log(result); // Output: NaN

3. Operations with Non Numeric Data

Performing math on incompatible data types also results in NaN:

let result = 25 * "Hello";
console.log(result); // Output: NaN

Detecting NaN

You can use the isNaN() function to check whether a value is NaN or cannot be converted into a valid number.

let nanExample = Number("Howdy!");
console.log(isNaN(nanExample)); // Output: true

Here, the string "Howdy!" cannot be converted into a number, resulting in NaN. The isNaN() function detects this and returns true.