How AI code goes wrong

Lesson 20 Edge cases

6 min read · JavaScript · Quiz

empty input, off-by-one, money in floats, time zones, Unicode, falsy zero

What you'll learn

  • Test every function against empty, one, zero and huge input
  • Recognise the traps in money, time zones and text
  • Predict where a happy-path function breaks

The AI tested the code with one friendly example, and it worked. Real users bring empty carts, zero quantities and names with emoji.

The idea

AI writes for the happy path: a normal user with a normal cart. The bugs live at the edges. Ask the same few questions of every function: what if it's empty? what if there is one item? what if it's zero or negative? what if it's huge?

Some inputs are traps in themselves: money as decimal numbers, dates without a time zone, text with emoji and accents, and zero treated as "nothing". You don't need to run the code in your head. Pick the nastiest input and see where the lines break.

invoiceSummary.js
1function invoiceSummary(lines) {2  let total = 0;3  for (const line of lines) {4    total += line.price * line.qty;5  }6  const tax = total * 0.0825;7  const biggest = Math.max(...lines.map((l) => l.price));8  const first = lines[0].name;9  return { total: total + tax, biggest, first };10}
  1. Line 3 On an empty list the loop just doesn't run: this part is safe. total stays 0.
  2. Line 6 Money as a decimal number. Float arithmetic has tiny errors, so keep money in whole cents.
  3. Line 7 With no lines, Math.max() returns -Infinity, not an error. A strange number flows on quietly.
  4. Line 8 With no lines this is undefined, and .name throws a TypeError. The empty cart crashes here.

Take away

  • Test every function with the empty, the one, the zero and the huge.
  • Money belongs in whole cents or a decimal type, never in float dollars.
  • Dates need a time zone and text needs a second look: emoji and accents break length checks.

Quiz: test yourself

7 questions: a quick quiz, then a review drill. Pick an answer to see why it's right.