Beginner · 8 min
Repeat with loops
Use for...of to process each item and accumulate a total.
Visit each value
for...of runs a block once for each value in an array. The loop variable holds the current value.
const names = ["Ada", "Mina"];
for (const name of names) {
console.log("Hello, " + name);
}Output
Hello, Ada Hello, Mina
Build a running total
Declare a running total with let before the loop. += adds a value to the current total. Display the result after the loop finishes.
const prices = [4, 6, 3];
let total = 0;
for (const price of prices) {
total += price;
}
console.log(total);Output
13
Put it into practice
- Predict the output of each example before running it.
- Complete the coding task, then try the practice questions.
Try it yourself
Code runs on this device. When you are signed in, drafts sync to your account.
Total the prices
Add every value in prices to total using the loop, then display total.
Add price instead of 0 inside the loop.