Skip to content
engineering workbench.by StudyPort Academy
All errors
data · DEBUG LIBRARY

NaN appearing where a number was expected

Locate the failed assumption, reproduce it, then repair the cause.

What actually caused it

is a special numeric value representing an invalid numeric result. A failed conversion, used in arithmetic, or an operation such as zero divided by zero can produce it. It then propagates through many later calculations.

User input usually arrives as text. A currency prefix, unit suffix, or non-numeric character may make Number return . Addition has another trap: it may concatenate the string instead of producing NaN, so the absence of NaN does not prove your types are correct.

has type number and is not equal to itself with ===. Test it with Number.isNaN rather than comparing value === NaN.

Minimal reproduction

Text that is not a whole number

const raw = "12px";
const width = Number(raw);
console.log(width * 2);

An empty collection divided by its length

const values = [];
const total = values.reduce((sum, value) => sum + value, 0);
console.log(total / values.length);

The fix

Validate empty input separately, convert explicitly, then check the numeric result. Number expects a whole numeric value; parseFloat accepts a numeric prefix, so choose it only when partial parsing is intended.

Number.isNaN checks specifically for without coercing. The global isNaN coerces first and can surprise you. Number.isFinite is often the better input check because it also rejects Infinity. After finding the first invalid result, repair that boundary rather than masking every later calculation with zero.

Validate an ordinary numeric input

const raw = "12";
const width = Number(raw);
if (raw.trim() === "" || !Number.isFinite(width)) {
  console.error("Enter a finite number");
} else {
  console.log(width * 2);
}

Choose an empty-input policy

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

This application defines the empty average as zero; another contract may reject it.