BugHunt

Unexpected NaN in a JavaScript calculation

Arithmetic on undefined, or on a string that is not a clean number, produces NaN — and every calculation that touches NaN is NaN too.

JavaScriptType errors

What it means

NaN ("not a number") is what JavaScript returns instead of throwing when arithmetic makes no sense. It spreads: NaN + 1 is NaN, so one bad value poisons a whole sum. It is also the only value not equal to itself — NaN === NaN is false — so checks with === never catch it.

Common causes

1. A missing property in a sum

One item without the field contributes undefined, and undefined + number is NaN.

Breaks

const total = cart.reduce((sum, item) => sum + item.price, 0);

Works

const total = cart.reduce((sum, item) => sum + (item.price ?? 0), 0);

2. Converting a string that is not a clean number

Number("1,000") and Number("12px") are NaN. parseInt("") is NaN too.

Breaks

const n = Number("1,000");

Works

const n = Number("1,000".replaceAll(",", ""));

3. A reduce without an initial value on objects

Without the 0, the first accumulator is the first object, and object + number is not a number.

Breaks

const total = items.reduce((sum, i) => sum + i.qty);

Works

const total = items.reduce((sum, i) => sum + i.qty, 0);

4. Checking for NaN with ===

NaN is never equal to anything, including NaN.

Breaks

if (value === NaN) { /* never runs */ }

Works

if (Number.isNaN(value)) { /* ... */ }

How to find it in your own code

Find the first NaN, not the last: log each operand of the calculation and look for undefined or a non-numeric string. Validate numbers where they enter the program (form fields, JSON, query strings) with Number.isFinite, so a bad value fails loudly at the boundary instead of quietly becoming NaN later.

Try it: fix this bug

easy

sumAll([1, 2, 3]) returns NaN instead of 6.

function sumAll(nums) {
    let total = 0;
    for (let i = 0; i <= nums.length; i++) {
        total = total + nums[i];
    }
    return total;
}
Open with hintsRuns in your browser. No account needed.

More challenges with this error

Each of these challenges runs into this exact error. Find the bug and fix it in your browser — no install, no account needed.

Still not sure why yours breaks?

Paste it into the visualizer and watch it run line by line, with every variable at every step. Free, and it runs in your browser.

Other common errors