LESSON 06 OF 10
Arrays and Loops
Store a list and repeat work for each item.
Before this lesson: complete the preceding lessons or review their examples. No installation or account is needed.
The idea
An array stores an ordered collection. Indexes start at zero, so items[0] reads the first entry. for...of visits the values in an iterable such as an array.
At a glance
| Syntax | Purpose |
|---|---|
array[index] | Read an item using its zero-based position |
.push(value) | Append an item and change the array |
for...of | Repeat a block for each value |
Try it yourself
Add another topic to the array and see the loop visit it.
Ready. Run the example to open its preview.
Console output
Not run yet.
Page preview
Expected result
Variables Study: Variables Study: Functions Study: Events Study: Practice 4
What to watch for
length is a count, so the last index is length - 1. Reading a missing index returns undefined. A while loop repeats while its condition is truthy; make sure its state can change so it eventually stops.
Your turn
Use a loop to total the numbers [5, 10, 15].
Show one solution
const minutes = [5, 10, 15];
let total = 0;
for (const value of minutes) {
total += value;
}
console.log(total);Check your understanding
What index reads the third item?
Index 2, because indexing starts at 0.