Skip to content

NaN Result

Quick summary

Your calculation resulted in `NaN` — usually because you mixed numbers with `undefined`, non-numeric strings, or other invalid values.

Why this happens

  • Parsed a non-numeric string with parseInt() or Number()

  • Performed arithmetic with undefined or a non-numeric value

  • Divided zero by zero (0 / 0) or took the square root of a negative number

Minimal example

✗ Broken code
const result = 10 + parseInt("abc");
console.log(result); // NaN
✓ Fixed code
const n = parseInt("abc") || 0;
const result = 10 + n;
console.log(result); // 10

parseInt("abc") returns NaN, and 10 + NaN is NaN — use || 0 to fall back to 0 when parsing fails.

How to diagnose

  • Log each operand to find which one is not a number

  • Use Number.isNaN() to check if a value is NaN (not the global isNaN)

  • Trace where the non-numeric value entered the calculation

How to fix

  • Validate inputs are numbers before performing arithmetic

  • Use Number(value) or parseFloat() explicitly and check the result

  • Provide a default value (e.g., const n = parseInt(str) || 0)

How to prevent

  • Validate numeric inputs at the boundary (API, user input)

  • Use Number.isNaN() instead of the global isNaN() to avoid type coercion

Related Resources

Related Glossary

Related Lessons

Related Practice

← Back to language