lecture 9 of 150 completed

Arrays and test data

Table rows, lists of cases and lists of elements are arrays. Learn the index, the length and what an empty list means.

What you'll learn

  • How positions in an array are counted
  • What you get when you read past the end
  • How a table of test cases is written as an array of objects

A test adds a book to Shelf and checks that it appears as the last row of the table. The test reads the last title and gets undefined, although the row is on the page.

const titles = ["Dune", "Emma", "Ulysses"];

console.log(titles.length);
console.log(titles[0]);
console.log(titles[titles.length]);
console.log(titles[titles.length - 1]);
3
Dune
undefined
Ulysses

An array is an ordered list of values. You write it in square brackets with commas between the items.

Each item has a position called its index. The first index is 0, not 1. So three items sit at 0, 1 and 2.

length is the number of items, which is 3. There is no item at index 3. Reading it gives undefined, with no error. The last item is always at length - 1.

Reading one position past the end is one of the most common mistakes in any language that counts from 0. In JavaScript it is quiet, so you only notice it when a later line uses the undefined.

Useful things an array can do

const titles = ["Dune", "Emma"];

titles.push("Ulysses");
console.log(titles.length);
console.log(titles.includes("Ulysses"));
console.log(titles.indexOf("Emma"));
console.log(titles.at(-1));
3
true
1
Ulysses
  1. push adds an item at the end.
  2. includes answers whether a value is in the list.
  3. indexOf gives the position of a value. It gives -1 when the value is not there.
  4. at(-1) reads from the end, so you do not have to write length - 1.

Test data is usually an array of objects

One object describes one thing. An array of objects describes many. This is how a table of test cases looks in code:

const feeCases = [
  { daysLate: 0, fee: 0 },
  { daysLate: 4, fee: 2 },
  { daysLate: 10, fee: 5 },
];

console.log(feeCases.length);
console.log(feeCases[1].fee);
3
2

feeCases[1] is the second object. .fee reads its property. The next lecture runs one check for every row of a table like this.

The empty list

An array can have no items. That is a normal value, written [].

const rows = [];

console.log(rows.length);
console.log(rows[0]);
0
undefined

Nothing here raises an error. When a page fails to load its rows, your test receives exactly this. The next two lectures show how such a list lets a test pass without checking anything.

Remember this

Positions start at 0, and the last item is at length - 1. Reading past the end gives undefined, not an error. An empty array is a normal value, so decide what your test should do with one.

Reference: Array on MDN.

now prove it

Reading is the setup. Solve this exercise in the editor. We run your code on each case and compare what it prints with the expected output.