typescript · level 1 · unit 6 · lesson 3
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
Three friends arrive. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
let friends: string[] = ["Mo", "Ana", "Kit"];
for (const friend of friends) {
console.log(`Hi ${friend}!`);
}
your turn
Your turn. Add up your shopping.
Type three prices, as numbers, into the array. Guess the total, then press run to check.
fix it
Three good scores, but a tiny total. Fix it!
- The total comes out as 4, the last score. What happens to the total on each lap?
total = scorethrows away the old total and keeps only this score. You want to add to it.- Change line 4 to total = total + score; then press run.
nailed it
you can add up a whole array. :D
for...ofvisits every item of an array in order.- Start a running total at 0, before the loop.
- Add each item to the total inside the loop.
new words in your collection
- for...of
- running total
This lesson isn’t saved. A free account remembers every lesson you finish.