Himanshu SharmaSoftware engineer
Let’s talk

JavaScript · Lesson 18 of 58

Loop practice: patterns and totals

Practise the loop patterns you will use constantly, such as totals, averages, counting, finding the largest value, building text and FizzBuzz.

15 minControl flowUpdated 14 November 2026

Awaiting technical review. This lesson is readable but not yet listed in search engines.

By the end of this lessonApply loops to common tasks, including accumulating a total, counting matches, finding a maximum, building a new array and printing a text pattern.

This lesson is practice. After it you will recognise the handful of loop shapes behind most beginner problems, and you will have written each one. You need the loops from for loops, while and do...while loops, break, continue and labels, and the conditions from earlier in this section.

For every example, run it, then change the data and predict the result before running again. Predicting is where the learning happens.

Pattern 1: add things up (accumulate)

Create a variable before the loop, then update it on every pass.

html
<pre id="out"></pre>
<script>
  const out = document.getElementById("out");
  const log = (...parts) => { out.textContent += parts.join(" ") + "\n"; };

  const prices = [120, 80, 45, 60];
  let total = 0;

  for (const price of prices) {
    total += price;
  }

  log("Total:", total);
  log("Average:", total / prices.length);
</script>

The output is Total: 305 and Average: 76.25. The key line is let total = 0; placed before the loop. The starting value of 0 is the neutral value for adding. For multiplying, it would be 1; for joining text, "".

Pattern 2: count matches

A counter goes up only when a condition holds.

html
<pre id="out"></pre>
<script>
  const out = document.getElementById("out");
  const log = (...parts) => { out.textContent += parts.join(" ") + "\n"; };

  const scores = [45, 82, 67, 91, 38, 74, 50];
  let passed = 0;

  for (const score of scores) {
    if (score >= 50) {
      passed++;
    }
  }

  log(passed, "of", scores.length, "passed");
</script>

This prints 5 of 7 passed. Notice that the if sits inside the loop, and the counter outside it.

Pattern 3: find the biggest (or smallest)

Keep a "best so far" and replace it whenever something beats it. The starting value is the part beginners get wrong.

html
<pre id="out"></pre>
<script>
  const out = document.getElementById("out");
  const log = (...parts) => { out.textContent += parts.join(" ") + "\n"; };

  const temperatures = [-8, -3, -20, -11];

  let wrongMax = 0;                 // looks harmless, but is not
  let max = temperatures[0];        // start from the first item
  let min = temperatures[0];

  for (const t of temperatures) {
    if (t > wrongMax) wrongMax = t;
    if (t > max) max = t;
    if (t < min) min = t;
  }

  log("wrong:", wrongMax);
  log("max:", max);
  log("min:", min);
</script>

The output is wrong: 0, max: -3 and min: -20. The "wrong" version reports 0, which is not even in the list, because no item beat the starting value. Starting from the first item (or from -Infinity for a maximum) always works. Later you will meet Math.max(...temperatures), which does this in one call, but writing the loop once teaches you how it works. This approach needs the array to have at least one item, so check for an empty array first.

Pattern 4: collect into a new array

Use push to add matching items to a fresh array.

html
<pre id="out"></pre>
<script>
  const out = document.getElementById("out");
  const log = (...parts) => { out.textContent += parts.join(" ") + "\n"; };

  const words = ["apple", "fig", "banana", "kiwi", "cherry"];
  const long = [];

  for (const word of words) {
    if (word.length > 4) {
      long.push(word.toUpperCase());
    }
  }

  log(long);
  log("count:", long.length);
</script>

This prints APPLE,BANANA,CHERRY and count: 3. Later in the course, filter and map do exactly this kind of loop for you (map, filter and reduce). Understanding the manual version makes those easier.

Pattern 5: build a string

Start with an empty string and add to it. This is how text patterns are made.

html
<pre id="out"></pre>
<script>
  const out = document.getElementById("out");
  const log = (...parts) => { out.textContent += parts.join(" ") + "\n"; };

  // A triangle of stars
  for (let row = 1; row <= 4; row++) {
    log("*".repeat(row));
  }

  // Reverse a word, letter by letter
  const word = "loop";
  let reversed = "";
  for (const letter of word) {
    reversed = letter + reversed;
  }
  log(word, "->", reversed);
</script>

The output is a four-line triangle, *, **, ***, ****, followed by loop -> pool. Putting the new letter in front of what you have so far reverses the order. "*".repeat(row) is a string method that repeats text; the Strings lesson covers its relatives.

Pattern 6: FizzBuzz, a classic

FizzBuzz is a famous warm-up task. For the numbers 1 to 15: print Fizz for multiples of 3, Buzz for multiples of 5, FizzBuzz for multiples of both, and the number itself otherwise.

html
<pre id="out"></pre>
<script>
  const out = document.getElementById("out");
  const log = (...parts) => { out.textContent += parts.join(" ") + "\n"; };

  for (let n = 1; n <= 15; n++) {
    if (n % 15 === 0) {
      log("FizzBuzz");
    } else if (n % 3 === 0) {
      log("Fizz");
    } else if (n % 5 === 0) {
      log("Buzz");
    } else {
      log(n);
    }
  }
</script>

The sequence is 1, 2, Fizz, 4, Buzz, Fizz, 7, 8, Fizz, Buzz, 11, Fizz, 13, 14, FizzBuzz, one per line. The order of the else if chain is the lesson: the "both" test comes first because of the first-match-wins rule you saw in if, else and else if.

Pattern 7: search with an early exit

Combine a loop, a condition and break to find the first thing that matches.

html
<pre id="out"></pre>
<script>
  const out = document.getElementById("out");
  const log = (...parts) => { out.textContent += parts.join(" ") + "\n"; };

  function isPrime(n) {
    if (n < 2) return false;
    for (let d = 2; d * d <= n; d++) {
      if (n % d === 0) return false;
    }
    return true;
  }

  const primes = [];
  for (let n = 1; n <= 30; n++) {
    if (isPrime(n)) primes.push(n);
  }
  log(primes);
</script>

This prints 2,3,5,7,11,13,17,19,23,29. A number is prime if no smaller number from 2 upward divides it. You only need to test divisors up to the square root, which is what d * d <= n expresses. Returning from inside the loop stops as soon as a divisor is found.

A debugging habit for loops

When a loop gives the wrong answer, add a log line inside it that prints the loop variable and your accumulator. Read the first pass, the second and the last. Nine times out of ten the problem is visible at an edge: the starting value, the first item, or the final pass.

Common mistakes

  • Declaring the accumulator inside the loop. let total = 0; inside the body resets it every pass, so you end up with just the last item.
  • Starting a maximum at 0 (or a minimum at 0). Negative numbers, or all-large numbers for a minimum, break it. Start from the first item.
  • Dividing by the wrong count. For an average, divide by prices.length, not by the last index, and guard against an empty array, where 0 / 0 is NaN.
  • Adding numbers that are strings. If data comes from a form, total += "5" joins text: "05". Convert with Number() first.
  • Ordering FizzBuzz tests wrongly. Test the combined case first.
  • Changing the array while looping. Build a new array instead of removing items from the one you are walking.

Exercise

Use this data: const orders = [250, 1200, 75, 430, 980, 15];

  1. Log the total of all orders.
  2. Log how many orders are 400 or more.
  3. Log the largest and smallest order, using the starting-from-the-first-item technique.
  4. Build a new array containing only the orders below 500, and log it.
  5. Challenge: log the second largest order using a loop. Think about which variables you need to keep track of.
  6. Challenge: print a right-aligned triangle of numbers, for example row 3 showing 1 2 3, up to 5 rows, by building each row as a string.

Once these feel comfortable, you have the foundation for the next section, where repeated code gets a name: Functions.

Key points

  • Most loops follow one of a few patterns: accumulate, count, find the best, collect into a new array, or build a string.
  • Create the accumulator (total, counter, best so far) before the loop, never inside it.
  • Start a maximum from the first item, or from -Infinity, not from 0, so negative numbers work.
  • Print or test the first and last pass by hand to catch off-by-one errors.
  • Later array methods such as map, filter and reduce express these patterns more briefly, but they are the same ideas.

Check yourself

1. Where should a running total variable be created?
2. Why is let max = 0 a poor starting value when finding the largest number in [-8, -3, -20]?
3. To find the average of an array you need the sum and...
4. In FizzBuzz, which check must come first?