NaN in Arithmetic: What It Means and How to Fix It
Error reference
NaN in Arithmetic
Language
Severity
MediumWhen it happens
NaN (Not a Number) is a special IEEE 754 value that propagates silently through calculations.
Potential fixes
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.
Related errors
Deep dive
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.
Potential fixes
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.
Examples
Code that triggers the error
const price = parseFloat("$19.99");
const tax = price * 0.2;
console.log(tax); // NaNError output
NaN
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.998Practice in English
How would you explain a NaN in Arithmetic to a fellow dev? Choose the right phrase:
"I hit an error...
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