#9 · Empty and null

Find the bug · #9 · Empty and null Medium JavaScript

A quantity of 0 is still charged

Setting an item’s quantity to 0 should take it out of the total, but it’s still charged once.

On this page

The report

Bug report

In the cart, setting an item’s quantity to 0 should remove it from the total. Instead it’s still charged as one.

The code

Read it first: what should it do? Then click the line where you think the bug is.

JavaScriptClick the line you think is wrong
// A cart line's total. A missing quantity means 1.
function lineTotal(item) {
  const qty = item.qty || 1;
  return qty * item.price;
}

Read it, then pick a line.

What it prints

Running it on a small example prints the output on the left. It should print the output on the right.

The example
console.log(lineTotal({ price: 250 }));
console.log(lineTotal({ price: 250, qty: 0 }));

It prints

250
250

It should print

250
0
Show the answer: the bug, the fix, and how you’d find it

The bug (line 3)

Line 3 uses || to give the quantity a default. But || replaces every falsy value, and 0 is falsy, so a real quantity of 0 becomes 1. The default should only apply when the quantity is missing, and ?? does exactly that: it replaces only null and undefined.

The fix

1// A cart line's total. A missing quantity means 1.2function lineTotal(item) {3  const qty = item.qty || 1;3  const qty = item.qty ?? 1;4  return qty * item.price;5}

How you’d find it

  1. Reproduce: price 250, quantity 0. You expect 0 and get 250, the same as a missing quantity.
  2. So 0 and “missing” are treated alike. Find where the default comes in: item.qty || 1.
  3. Check what || does: it falls back for 0, "", NaN, null, undefined and false. The intent was only “missing”.

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(lineTotal({ price: 250, qty: 0 }), 0);
assert.equal(lineTotal({ price: 250 }), 250);
assert.equal(lineTotal({ price: 250, qty: 3 }), 750);

Where else this bites

  • price || defaultPrice turns a free item (price 0) into the default price.
  • Python’s x or default has the same trap with 0, "" and [].
Your progress stays on this device.