Skip to content

How to Fix NaN in JavaScript Calculations

DodaTech Updated 2026-06-24 3 min read

In this tutorial, you'll learn about How to Fix NaN in JavaScript Calculations. We cover key concepts, practical examples, and best practices.

The Problem

JavaScript returns NaN (Not-a-Number) from arithmetic operations when one or more operands are not valid numbers, typically from parsing failures, undefined variables, or type coercion errors.

Quick Fix

Step 1: Validate input before arithmetic

Parsing a non-numeric string returns NaN:

const price = parseFloat('ten dollars');
const total = price * 2;
console.log(total);
NaN

Validate the parsed result:

const price = parseFloat('ten dollars');
if (isNaN(price)) {
    console.error('Invalid price input');
} else {
    const total = price * 2;
    console.log(total);
}

Step 2: Convert strings to numbers explicitly

String concatenation takes precedence over addition:

const a = '5';
const b = '10';
const sum = a + b;
console.log(sum);
'510'

Convert explicitly:

const a = '5';
const b = '10';
const sum = Number(a) + Number(b);
console.log(sum);
15

Step 3: Handle undefined or null values

Operations with undefined produce NaN:

function calculatePrice(price, tax) {
    return price + tax;
}
console.log(calculatePrice(100));
NaN

Provide defaults:

function calculatePrice(price, tax = 0) {
    return price + tax;
}
console.log(calculatePrice(100));
100

Step 4: Check for division by zero

Division by zero returns Infinity, not NaN:

function average(values) {
    if (values.length === 0) return NaN;
    return values.reduce((a, b) => a + b, 0) / values.length;
}
console.log(average([]));
NaN

Guard against empty arrays:

function average(values) {
    if (!values || values.length === 0) return 0;
    return values.reduce((a, b) => a + b, 0) / values.length;
}
console.log(average([]));
0

Step 5: Use Number.isNaN instead of global isNaN

The global isNaN coerces inputs:

console.log(isNaN('hello'));
console.log(Number.isNaN('hello'));
true
false

Use Number.isNaN for stricter checking.

Prevention

  • Validate all numeric inputs with Number.isFinite() before calculations.
  • Provide default values for optional numeric parameters.
  • Use Number() or parseFloat() with validation instead of relying on coercion.
  • Test edge cases (empty arrays, missing values, zero, negative numbers).
  • Use TypeScript with strict numeric types to catch NaN at compile time.

Common Mistakes with nan error

  1. Mixing let bindings with <- bindings in do notation, producing type errors
  2. Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
  3. Non-exhaustive pattern matches that compile with warnings then crash at runtime

These mistakes appear frequently in real-world JS code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

### What is the difference between NaN and Infinity?

NaN represents a value that is not a valid number (0/0, parseFloat('abc')). Infinity represents a number too large to represent (1/0). Both are of type number. Check for NaN with Number.isNaN(). Check for Infinity with Number.isFinite() or isFinite().

Why does typeof NaN return 'number'?

NaN is a numeric value according to the IEEE 754 floating point standard. It represents an undefined or unrepresentable numeric result. The typeof operator returns 'number' because NaN is defined in the number type, even though it represents "not a number."

How do I check if a value is a valid number?

Use Number.isFinite(value). This returns true only for finite numbers (not NaN, Infinity, -Infinity, or non-numeric types). For parsing results, first use Number(value) and then check with Number.isFinite(). This is more reliable than typeof value === 'number'.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro