How to Fix NaN in JavaScript Calculations
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()orparseFloat()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
- Mixing let bindings with <- bindings in do notation, producing type errors
- Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
- 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
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro