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.
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.
Starting a maximum at 0 is a classic bug when all values can be negative. Start at the first element, or -Infinity, and decide explicitly what an empty input returns.
Several statistics can be computed in a single pass (sum, count, min and max together), which matters for large data or streams.
Array methods encode these patterns: reduce (accumulator), filter(...).length (counter), Math.max(...arr) (maximum, limited by argument count), find/some (search). Knowing the loop version helps you understand and debug them.
Write the edge cases as tests first: empty array, one element, all equal, negative numbers, ties. Problem solving is as much about defining behaviour at the edges as about the main loop.
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.
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.
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}`);
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`);
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
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.
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 explanationLoop 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 predictionPattern 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.
DebuggingWrong 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 generationData 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 reviewPlanning
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.