CyberStars

Arrays

A shopping list isn't one thing. It's milk, bread and apples, one after the other. You could keep each one in its own variable, item1, item2, item3... but what if the list has 30 things? JavaScript has one value that holds a whole list: an array.

Making an array

You write an array in square brackets, with commas between the values:

const shopping = ["milk", "bread", "apples"];
console.log(shopping);
["milk", "bread", "apples"]

One name, three values, in order. An array can hold numbers too, or a mix: [3, 7, 12].

Reading one item: its index

Each item has a number for its place, called its index. And here is the surprise: counting starts at 0:

console.log(shopping[0]);
console.log(shopping[1]);
console.log(shopping[2]);
milk
bread
apples

shopping[0] is the first item, and shopping[1] is the second. Think of a building: in many countries, the ground floor is floor 0, and the first floor is one up.

The number of items

Like a string, an array has a length:

console.log(shopping.length);
3

So the last item is always at length - 1: here, shopping[2]. Counting starts at 0, so the last index is one less than the number of items.

Break it on purpose

Ask for the item at the length:

console.log(shopping[3]);
undefined

There is no fourth item. undefined is JavaScript's word for "there's nothing there". When you get it, check your index: usually it's one too many.


Mission: The shifts

What you will see: when crew.html opens, the console shows these lines, with its other lines:

First shift: Morning
Last shift: Night

The station has three shifts a day: Morning, Day and Night, in that order.

  • In crew.js, the three shifts are kept in one array, in that order.
  • The console shows First shift: Morning.
  • The console shows Last shift: Night.
  • Each shift is read from the array by its index.