×

typescript · 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.

A for...of loop walks along an array, one item at a time. for (const coin of coins) reads like plain English: for each coin of the coins, run the block.

Each lap, coin is a fresh box holding the next item. It can be a const, because nothing changes it inside the block. There is no counter to manage and no index to get wrong.

To add things up, keep a . Start a box at 0 before the loop, add each item to it inside, and show it after the loop ends.

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

Name the lap box after one item, like coin for coins, so the loop reads clearly.