Lingua-e
JavaScript

What is a NaN in Arithmetic?

← Errors

NaN (Not a Number) is a special IEEE 754 value that propagates silently through calculations. Once a NaN enters a computation, every subsequent result is also NaN. It is produced by invalid numeric operations like parsing non-numeric strings or dividing zero by zero.

Why it happens

  • Calling parseInt() or parseFloat() on a string that does not begin with a number.
  • Performing arithmetic on undefined (undefined + 1 === NaN).
  • Using Math functions with non-numeric input (Math.sqrt(-1)).
  • An array reduction with no initial value on an empty array.

Examples

JavaScript

Code that triggers the error

const price = parseFloat("$19.99");
const tax = price * 0.2;
console.log(tax); // NaN

Error output

NaN

How to fix it

Validate numeric input before arithmetic. Use Number.isNaN() (not the global isNaN()) to check for NaN since isNaN('') returns true. Always provide an initial value to Array.reduce(). Strip currency symbols and formatting before parsing money values.

Fixed code

const raw = "$19.99";
const price = parseFloat(raw.replace(/[^0-9.]/g, ""));
if (isNaN(price)) throw new Error(`Cannot parse price: ${raw}`);
const tax = price * 0.2;
console.log(tax); // 3.998

Related errors

Ready to practice your English at work?

Lingua-e has interactive exercises built around real developer conversations: standups, code reviews, retrospectives, and more. Practice until it comes naturally.

Try Lingua-e for free