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
| Method | What 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
- Add
"Saturn"to the end of theplanetsarray with a method. - Change the first item from
"Mercury"to"Venus". - Use a
for…ofloop to print every planet on its own line. - After the loop, print how many planets are in the array.
"Saturn"is added to the end withpush- The first item is now
"Venus" - A
for…ofloop prints all four planets in order - The number of planets,
4, is printed last
Lesson complete!
Next Lesson: Working With Lists