×

javascript · level 3 · unit 3 · lesson 3

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

A runs your code and asserts what the answer should be.

Checking output by eye stops working once a program grows. A test does the checking for you: run a function with a known input and compare the real answer with the one you expect.

The comparison is an . assertEqual below throws when the two differ, so a wrong answer can never slip past. Two arrays are only === when they are the very same array, so it compares their JSON text instead.

Test the normal cases and the edge cases: empty arrays, zero, the first and the last item.

function assertEqual(actual, expected) {
  const a = JSON.stringify(actual);
  const e = JSON.stringify(expected);
  if (a !== e) { throw new Error(`Expected ${e} but got ${a}`); }
  console.log(`ok ${a}`);
}
function evens(numbers) { return numbers.filter((n) => n % 2 === 0); }
assertEqual(evens([1, 2, 3, 4]), [2, 4]);
assertEqual(evens([]), []);
assertEqual(evens([7]), []);

Write the expected answer yourself, by hand, before you run the code.