Skip to the content

Edge cases

JavaScript · Unit 20: Testing and debugging

Bugs hardly ever live in the middle of the data: they live at the edges. The empty array, zero, a negative, a value that never arrived.

Those are called edge cases, and with normal data this function looks perfect.

const add = (a, b) => a + b;
function average(ns) {
  const t = ns.reduce(add, 0);
  return t / ns.length;
}
console.log(average([4, 6]));

Prints

5

The rest of the explanation is in the lesson, which is part of the full plan.

Exercises in this lesson

You do them in the app, which checks them on the spot and explains why.

  1. 1. Predict the output

    Same function, now with an array holding no numbers. What does it print?

  2. 2. Complete the code

    Complete the guard so an empty array gives 0 and the other case stays the same.

  3. 3. Find the case that fails

    biggest(ns) gives back the largest number in the array, or 0 if it's empty. Which call does it fail on?

  4. 4. Predict the output

    What does this code print?

  5. 5. Find the bug

    shipping(kg) charges 20 per kilo, and should only say No data when nothing is passed in. shipping(0) should print 0. Which line has the bug?

  6. 6. Multiple choice

    You already tested initials with two names. Which call is worth trying next?

  7. 7. Predict the output

    The edge case here is the empty text. What does it print?

  8. 8. Put the lines in order

    Put first(ns) in order: it gives back the first item of the array, or the text empty if there isn't one.

  9. 9. Find the case that fails

    discount(p, pct) takes that percentage off the price p, and leaves the price alone if no percentage is passed in. Which call does it fail on?

  10. 10. Predict the output

    Two tests for parts, which counts pieces separated by commas. What does it print?

Do this lesson

It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.

See all lessons →