Sikau

JavaScript · Day 20 · about 25 min

Loop patterns

Totals, counts and finding the biggest.

Three patterns you'll use forever

Most loops in real programs do one of three jobs: add things up, count things, or find the biggest (or smallest). Learn these patterns and you'll recognise them everywhere.

Pattern 1: the running total

Start a total at 0, then add to it each time around. The variable that collects the result is called an accumulator.

let total = 0;
for (let i = 1; i <= 5; i++) {
  total += i;
}
console.log(total);

The rest of this lesson

  • Pattern 2: counting · Pattern 3: the biggestexplain
  • Combining patternsexplain
  • Predict the outputpredict
  • Total of odd numberspredict
  • Your turnwrite code
  • Challengechallenge
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 68 lessons of JavaScript