×

javascript · level 1 · unit 6 · lesson 3

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

A loop visits every item in an array.

Think of a checkout. The cashier picks up each thing in your basket, one at a time, and beeps it. for (let coin of coins) does the same: each turn, coin holds the next item.

No counting needed. A for...of loop runs once for every item, then stops by itself after the last one.

To add things up, keep a . Start a variable at 0 before the loop. Each turn, add the item to it. After the loop, it holds the full total.

let coins = [2, 5, 1, 2];
let total = 0;
for (let coin of coins) {
  total = total + coin;
}
console.log("Piggy bank:", total);

Need the index as well? A for loop can count it: for (let i = 0; i < coins.length; i++).