Find the bug · #7 · Empty and null Easy JavaScript
The dashboard shows NaN
A new store’s dashboard shows “NaN” where the average order value should be.
On this page
The report
The sales dashboard shows the average order value. On a brand-new store with no orders yet, the card says NaN.
The code
Read it first: what should it do? Then click the line where you think the bug is.
// The average order value for the dashboard.
function averageOrder(orders) {
let total = 0;
for (const o of orders) total += o.amount;
return Math.round(total / orders.length);
}Read it, then pick a line.
What is the average of no orders at all? What does the code work out?
What it prints
Running it on a small example prints the output on the left. It should print the output on the right.
console.log(averageOrder([{ amount: 100 }, { amount: 300 }]));
console.log(averageOrder([]));It prints
200 NaN
It should print
200 0
Show the answer: the bug, the fix, and how you’d find it
The bug (line 5)
Line 5 divides by orders.length. With no orders that’s 0 / 0, which in JavaScript isn’t an error: it’s NaN, and it flows straight to the screen. An empty list needs its own answer, here 0.
The fix
2function averageOrder(orders) {3 let total = 0;4 for (const o of orders) total += o.amount;5 return Math.round(total / orders.length);5 return orders.length === 0 ? 0 : Math.round(total / orders.length);6}How you’d find it
- Reproduce the case the report points at, a store with no orders:
averageOrder([])givesNaN. NaNusually means arithmetic on nothing:undefined, or0 / 0. Heretotalis 0 and so isorders.length.- Decide what the average of no orders should be (0, or “no data yet”) and handle it before dividing.
The test that catches it
It fails on the code above and passes once it’s fixed. Keep it, so the bug can’t come back.
assert.equal(averageOrder([]), 0);
assert.equal(averageOrder([{ amount: 50 }]), 50);Where else this bites
- Percentages and conversion rates on a day with zero visitors.
- Python raises
ZeroDivisionErrorfor the same thing; Java’s integer division throws, while dividing doubles gives NaN.