Skip to the content

Project: test a function

JavaScript · Unit 20: Testing and debugging

You have three versions of the same function, average: one is right and the other two each have a different bug.

Your job isn't to fix them, it's to write the tests that catch the two bad ones and pass the good one.

function total(ns) {
  return ns.reduce((a, b) => a + b, 0);
}
function v2(ns) {
  if (ns.length === 0) {
    return 0;
  }
  return total(ns) / ns.length;
}
console.log(v2([2, 4]));

Prints

3

Exercises in this lesson

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

  1. 1. Predict the output

    These are the two buggy versions, each with its own case. What do they print?

  2. 2. Complete the code

    Complete the check so it warns you when the average of 2 and 4 isn't 3.

  3. 3. Write the code

    Write test(n): it takes the version number (1, 2 or 3) and gives back the text ok if that version gets the average right, or BAD if you find a bug in it. The average of an empty array is 0. You need at least two checks, because each bad version fails on a different case.

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 →