JavaScript Basics · Lesson 8 of 13

Arrays

An array is an ordered list of values, written in square brackets:

const fruits = ["apple", "banana", "cherry"];

Positions start at zero

Each item has a position, called its index. The first item has index 0:

console.log(fruits[0]);       // "apple"
console.log(fruits[2]);       // "cherry"
console.log(fruits.length);   // 3

The last item is always at length - 1. Counting from zero feels odd for a day or two and then becomes natural.

You can replace an item by assigning to its index: fruits[1] = "blueberry";

Adding and removing

MethodWhat it does
.push(x)adds x to the end
.pop()removes the last item and returns it
.unshift(x)adds x to the start
.shift()removes the first item and returns it
.includes(x)true if x is in the array
.indexOf(x)position of x, or -1 if it is not there

An array made with const can still be changed with these methods. const only stops you from replacing the whole array with a different one.

Looping over an array

The for…of loop runs once for each item, putting the item in a variable:

for (const fruit of fruits) {
  console.log(fruit);
}

When you also need the index, use a counting loop from 0 while i < fruits.length.

Your Task

  1. Add "Saturn" to the end of the planets array with a method.
  2. Change the first item from "Mercury" to "Venus".
  3. Use a for…of loop to print every planet on its own line.
  4. After the loop, print how many planets are in the array.
  • "Saturn" is added to the end with push
  • The first item is now "Venus"
  • A for…of loop prints all four planets in order
  • The number of planets, 4, is printed last