JavaScript · Unit 3: Working with data · Lesson 2 of 6
Looping over arrays
for...of visits each item of an array in turn: for (const color of colors) { ...
Opens this lesson in Code Academy. Lessons open one after another, and each unit opens when you pass the checkpoint quiz before it (you can take a checkpoint early to skip ahead). If this lesson is not open yet, the button shows you its unit on your map.
The idea
for...of visits each item of an array in turn: for (const color of colors) { ... }. It reads well and you cannot get the index wrong.
Use the classic for loop when you also need the index: for (let i = 0; i < colors.length; i++) { ... colors[i] ... }
A common pattern: start a result before the loop (a total of 0, an empty array) and update it for each item.
Worked example
JavaScript
const prices = [4, 10, 6];
let total = 0;
for (const price of prices) {
total = total + price;
}
console.log(total);
It prints
20
Key terms
- for loop
- Repeats code with a start, a condition and a step. for...of visits each item of an array.
Practise it in Code Academy
It has 4 exercises (predict the output, multiple choice, fix the broken code and write code from a prompt) and takes about 7 minutes. Every answer is checked as you go, and feedback names the exact mistake. Hints and the solution are there if you get stuck.
Every lesson is free: no ads, no lives and no paywall.