This is where arrays and loops become best friends. Since arrays have a length and numbered indexes, a for loop can visit every item:
const planets = ["Mercury", "Venus", "Earth", "Mars"];
for (let i = 0; i < planets.length; i++) {
console.log(`Planet ${i + 1}: ${planets[i]}`);
}
It prints
Planet 1: Mercury Planet 2: Venus Planet 3: Earth Planet 4: Mars
Notice we print i + 1 so humans see "Planet 1" instead of "Planet 0." Computers count from zero; people count from one. Be kind to your users.
for...of: the friendlier loop
Most of the time, you don't actually need the index. You just want each item, one at a time. For that, the for...of loop (which you met with strings in Grade 5) is much cleaner:
const planets = ["Mercury", "Venus", "Earth", "Mars"];
for (const planet of planets) {
console.log(`Hello, ${planet}! 🪐`);
}
It prints
Hello, Mercury! 🪐 Hello, Venus! 🪐 Hello, Earth! 🪐 Hello, Mars! 🪐
Read it as: "for each planet of the planets array, do this." No counter, no length, no off-by-one errors. Lovely.
Common array recipes
Here are a few patterns you'll use again and again. Learn these and you can answer almost any question about a list.
Adding everything up:
const prices = [12, 45, 8, 30];
let total = 0;
for (const price of prices) {
total += price;
}
console.log(`Total: $${total}`);
console.log(`Average: $${total / prices.length}`);
It prints
Total: $95 Average: $23.75
Finding the biggest:
const temperatures = [28, 31, 35, 29, 33];
let hottest = temperatures[0];
for (const temp of temperatures) {
if (temp > hottest) {
hottest = temp;
}
}
console.log(`The hottest day was ${hottest}°C`);
It prints
The hottest day was 35°C
(The trick: start by assuming the first item is the biggest, then check every item to see if there's a bigger one.)
Counting matches:
const scores = [45, 78, 90, 32, 66, 51];
let passed = 0;
for (const score of scores) {
if (score >= 50) {
passed++;
}
}
console.log(`${passed} out of ${scores.length} students passed.`);
It prints
4 out of 6 students passed.
Building a new array:
const numbers = [1, 2, 3, 4, 5];
const doubled = [];
for (const n of numbers) {
doubled.push(n * 2);
}
console.log(doubled);
It prints
[ 2, 4, 6, 8, 10 ]
These four patterns (sum, max, count, build) are so common that JavaScript has special shortcut methods for them. You'll learn those in Grade 10, and they'll blow your mind. But it's important to understand the loop versions first, because that's what the shortcuts do behind the scenes.