Lesson 5 of 8

Off-by-one errors

Goal

Test the edges before the middle

01

Explanation

The off-by-one error is the best-known loop bug: the loop starts one step after the first element, stops one step before the last, or runs one step past it, and the code looks perfectly fine when you read it.

One rule fixes most of them: array indexes start at 0 and end at length - 1. Reading list[list.length] doesn't throw an error. It quietly returns undefined, which is why "undefined" shows up on the page without anything crashing.

To catch it, test the edges, not the middle: an empty list, a one-element list, and the first and last elements. That's where this bug always hides.

02

Your task

Fix the loop in newestFirst(list) so it returns all the messages from newest to oldest, with no undefined, and without changing the original array.

Checks

6 checks
  1. The loop doesn't read past the last index
  2. The oldest element isn't lost
  3. A one-element list stays the same
  4. An empty list gives an empty list
  5. The original array doesn't change
  6. The page shows all four messages from newest to oldest
03

Hints

0/3
index.html
Preview
index.html100%
–/6

Press “Run and check” to grade your code.

6 checks listed under “Your task”.