JavaScript AcademyProfessional Engineering
Level 1 · FoundationsModule 4: Repetition and Problem-SolvingLesson 20 of 150About 50 minutes

Lesson 20: Solving problems with iteration

01Opening question

Given a month of daily sales, how would you find the best day, the average and how many days beat a target, using only loops?

Keep the question in mind. By the end of the lesson you will be able to answer it, and prove it with working code.

02Start with working code

This is the maximum pattern: start with the first value and replace it whenever a bigger one appears.

const sales = [120, 340, 90, 410, 260];
let best = sales[0];
for (const value of sales) {
  if (value > best) best = value;
}
console.log("Best day:", best);

03Objective and prerequisites

Learning objective: Solve problems with the accumulator, counter, maximum/minimum and search patterns, plan a loop before writing it, and test it with edge cases.

You need: Lesson 16: For loops, Lesson 17: While and do-while loops, Lesson 18: Break and continue, Lesson 19: Nested loops and patterns

Skills practised: Problem solving, Loops, Loop algorithms.

04Explanation

Most loop problems use a small set of patterns. Learn them and you can combine them for new problems.

Accumulator: start at 0 (or "" or []) and add to it each pass, e.g. a total. Counter: start at 0 and add 1 when a condition is true, e.g. days over target.

Maximum/minimum: start with the first value and replace it when a bigger (or smaller) one appears. Search: loop until you find a match, then stop with break.

Plan before coding: write the input, the output, the variables you need before the loop, what changes inside it, and what you print after it. Then test with normal data, an empty list and a single item.

05Definitions

Accumulator pattern
A variable that collects a result, such as a sum, across iterations.
Counter pattern
A variable that counts how many items meet a condition.
Maximum pattern
Keeping the largest value seen so far and replacing it when a larger one appears.
Linear search
Checking items one by one until a match is found.
Edge case
An unusual input, such as an empty list, that a solution must still handle.

Open the full glossary

06Visual learning object

Algorithm state tracker. Step through an accumulator, counter and maximum in one loop and watch each variable change.

Loading the interactive object…

Open the full While-loop visualizer page with its guided experiment.

07Examples

ex-020-01Total and average Browser-executable JavaScript

An accumulator gives the total; dividing by the count gives the average.

const scores = [72, 85, 90, 64];
let sum = 0;
for (const s of scores) {
  sum += s;
}
const average = sum / scores.length;
console.log("Sum:", sum, "Average:", average);
Sample input
None
Expected output
Sum: 311 Average: 77.75
Common mistake
Dividing inside the loop instead of after it.
Try this
Round the average to one decimal place with toFixed.
Source
examples/ex-020-01-accumulator-average.js

ex-020-02Counting matches Browser-executable JavaScript

A counter only increases when the condition is true.

const temps = [18, 24, 27, 22, 30, 19];
let warmDays = 0;
for (const t of temps) {
  if (t >= 25) warmDays++;
}
console.log(`${warmDays} warm days out of ${temps.length}`);
Sample input
None
Expected output
2 warm days out of 6
Common mistake
Counting with warmDays = 1 instead of adding one.
Try this
Also count cold days below 20.
Source
examples/ex-020-02-counter.js

ex-020-03Minimum and maximum together Browser-executable JavaScript

Start from the first value so negative data works.

const changes = [-4, -12, -1, -7];
let lowest = changes[0];
let highest = changes[0];
for (const c of changes) {
  if (c < lowest) lowest = c;
  if (c > highest) highest = c;
}
console.log("Lowest:", lowest, "Highest:", highest);
Sample input
None
Expected output
Lowest: -12 Highest: -1
Common mistake
Starting highest at 0, which reports 0 though no value is 0.
Try this
Track the index of the lowest value too.
Source
examples/ex-020-03-min-max.js

ex-020-04A number problem Browser-executable JavaScript

A while loop takes digits off a number one at a time.

let n = 4096;
let digitSum = 0;
while (n > 0) {
  digitSum += n % 10;
  n = Math.floor(n / 10);
}
console.log("Digit sum:", digitSum);
Sample input
None
Expected output
Digit sum: 19
Common mistake
Forgetting Math.floor, which leaves decimals and never reaches 0 cleanly.
Try this
Count the digits instead of adding them.
Source
examples/ex-020-04-digit-sum.js

08Guided exercises

Three exercises: explore and modify, complete the implementation, then build independently. Tests check behaviour, so any correct solution passes.

Fix the maximum

Start a maximum from real data instead of 0.

const lossesPerDay = [-30, -5, -12];
let smallestLoss = 0;
for (const v of lossesPerDay) {
  if (v > smallestLoss) smallestLoss = v;
}
console.log("Smallest loss:", smallestLoss);

Sales summary

Combine accumulator, counter and maximum in one loop.

const sales = [220, 480, 150, 510, 300];
const TARGET = 250;
// TODO: one loop that finds total, daysOverTarget and bestDay

First repeated ticket

Plan and write a search with nested loops and an early exit.

const tickets = ["T4", "T9", "T2", "T9", "T4"];

09Prediction

Commit to an answer first, then run the real code to compare.

const nums = [3, 8, 2, 8];
let count = 0;
let max = nums[0];
for (const n of nums) {
  if (n > max) { max = n; count = 1; }
  else if (n === max) count++;
}
console.log(max, count);

What is printed?

10Debugging investigation

The average shows NaN for a new user

A new user with no workouts sees Average: NaN minutes on their dashboard.

const workouts = [];
let sum = 0;
for (const minutes of workouts) {
  sum += minutes;
}
const average = sum / workouts.length;
console.log(`Average: ${average} minutes`);

More cases in the Debugging Detective Laboratory

11Practical scenario

Fitness summary

A step-counter app shows weekly total, average, best day and how many days hit 10,000 steps. Every figure comes from the same loop patterns.

const steps = [8000, 12000, 9500];
let total = 0;
let goalDays = 0;
for (const s of steps) {
  total += s;
  if (s >= 10000) goalDays++;
}
console.log(total, goalDays);

12Knowledge check

1. Which pattern finds how many items meet a condition?

  • Accumulator
  • Counter
  • Maximum
  • Search

2. What is printed?

const a = [-9, -2];
let max = 0;
for (const v of a) if (v > max) max = v;
console.log(max);
  • 0
  • -2
  • -9
  • undefined

3. Why is the average wrong?

let sum = 0;
for (const v of [2, 4]) {
  sum += v;
  sum = sum / 2;
}
  • sum should start at 1
  • It divides inside the loop
  • length is wrong
  • for...of cannot add

4. Which is an important edge case for an average?

  • A list of 100 items
  • An empty list
  • A list of positive numbers
  • Sorted numbers

5. What is printed?

let n = 123, s = 0;
while (n > 0) { s += n % 10; n = Math.floor(n / 10); }
console.log(s);
  • 6
  • 123
  • 321
  • 0

6. Total, count and max are needed. Which is better for large data?

  • Three separate loops
  • One loop updating all three
  • They are identical
  • Nested loops

13Solutions and tests

Each exercise's solution appears in the exercise once you have run its tests. Solutions are one possible answer: the tests accept any implementation with the same behaviour.

Automated acceptance tests for this lesson

These are the same checks the exercises run. They are visible on purpose: client-side tests help you learn and are not secret.

  • Fix the maximum: Prints -5; Starts from the data
  • Sales summary: Prints the summary; Values are correct; One loop only
  • First repeated ticket: Prints T9; repeated is T9
  • ex-020-01: output matches the documented expected output
  • ex-020-02: output matches the documented expected output
  • ex-020-03: output matches the documented expected output
  • ex-020-04: output matches the documented expected output

Download the whole lesson folder (examples, exercises, solutions, tests) as ZIP

14Source files

The lesson lives in the companion repository at curriculum/level-01-foundations/module-04-repetition-and-problem-solving/lesson-020-solving-problems-with-iteration/. Every example on this page is generated from those files.

These links open the files in the GitHub repository (https://github.com/lsvekis/JavaScript-Professional-Engineering-Academy). You can also use the ZIP download above.

15Summary and next steps

  • Accumulator, counter, maximum/minimum and search are the core loop patterns.
  • Start a maximum from the data, not from 0.
  • Plan input, variables, loop body and output first.
  • Test empty, single and negative inputs.

16AI learning prompts

Copy a prompt into the AI assistant of your choice. Then verify what it says by running code here. No AI service is connected to this page.

Concept explanation Loop patterns
Context: I can write loops.
Task: Explain the accumulator, counter, maximum and search patterns with one example each.
Constraints: Beginner level.
Expected behaviour: I can name the pattern a problem needs.
Testing: Give me five problems to classify.
Code prediction Pattern tracing
Context: I know the four patterns.
Task: Give me five short programs combining them and ask what each prints.
Constraints: Wait for my answers.
Expected behaviour: Include negative numbers.
Testing: Explain with a trace table.
Debugging Wrong maximum
Context: My maximum is 0 when all values are negative.
Task: Help me find the starting value problem with questions.
Constraints: No direct answer.
Expected behaviour: I fix it myself.
Testing: Suggest edge-case tests.
Exercise generation Data problems
Context: I finished the sales summary.
Task: Create three problems that need two or more loop patterns.
Constraints: Fictional data, exact output.
Expected behaviour: Include an empty-list edge case.
Testing: Include expected output.
Code review Planning
Context: Here is my plan and my loop for a weekly report.
Task: Check that my plan and code match and that edge cases are handled.
Constraints: Do not rewrite everything.
Expected behaviour: Every edge case has a defined result.
Testing: List missing tests.