javascript · 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.
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++).
guess first
The total is shown inside the loop. What appears?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
let dailySteps = [3000, 4000, 2000];
let total = 0;
for (let steps of dailySteps) {
total = total + steps;
console.log(total);
}
your turn
Your turn. Add up your shopping.
Type three prices as numbers, with no quotes, then press run to see the total.
fix it
Three scores, but the total is 4. Fix it!
- The total ends up as the last score only. What happens to the total on each turn?
- Line 4 overwrites the total with each score. It should add the score to what is already there.
- Change line 4 to total = total + score; then press run.
nailed it
you added up a whole array. :D
- A
for...ofloop visits every item, 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.