SECTION 1
Historical Context & Motivation
Long before modern computers existed, mathematicians faced a familiar challenge: how do you process a large collection of numbers without doing each operation by hand? The answer has always involved repetition — performing the same small action over and over until you reach the end of the data. Early calculating machines were built specifically to automate this kind of repetitive work, and the concept of a loop became one of the most important ideas in computer science.
1843 • Ada Lovelace's First Algorithm
1945 • Von Neumann Architecture
1957 • FORTRAN's DO Loop
1995 • JavaScript Is Born
Despite all the advances in programming languages, the core question remains the same: when you have a collection of data — scores, prices, temperatures, names — how do you efficiently count items, sum values, find the minimum or maximum, or search for a specific item? These four tasks are the loop patterns you will learn in this lesson.
SECTION 2
Core Principles & Definitions
A loop pattern is a reusable strategy — think of it like a recipe — for solving a common category of problem using a loop. Every loop pattern follows a three-part structure: you initialize a variable before the loop, update it inside the loop body, and use the final value after the loop ends. Understanding these patterns means you do not have to reinvent a solution every time you encounter a new dataset.
Counting Pattern
Summing Pattern
Min / Max Pattern
Searching Pattern
KEY TAKEAWAY
SECTION 3
Visual Explanation — The Loop Pattern Blueprint
Notice how each pattern has a different starting value and a different update rule. The counting pattern starts at 0 and adds 1 each time a condition is met. The summing pattern also starts at 0 but adds the actual data value. The min/max pattern starts at the first element and replaces the tracker whenever a better candidate appears. The searching pattern starts with false (or −1) and flips to true (or the index) upon a match. Once you memorize these differences, you can write any of these loops from memory in seconds.
SECTION 4
How Each Pattern Works — Step by Step
Let's walk through the mechanics of each pattern using a concrete array: let scores = [88, 72, 95, 63, 88, 91];. Imagine this represents six students' test scores in your class. We will trace what the accumulator variable holds after each iteration.
Counting: How Many Scores Are 85 or Above?
We initialize let count = 0. The loop checks each score: 88 ≥ 85? Yes, count becomes 1. 72 ≥ 85? No, count stays 1. 95 ≥ 85? Yes, count becomes 2. 63 ≥ 85? No. 88 ≥ 85? Yes, count becomes 3. 91 ≥ 85? Yes, count becomes 4. After the loop, count is 4. Four students scored 85 or above.
Summing: What Is the Total of All Scores?
We initialize let total = 0. Each iteration adds the current score: 0 + 88 = 88, then 88 + 72 = 160, then 160 + 95 = 255, then 255 + 63 = 318, then 318 + 88 = 406, and finally 406 + 91 = 497. The sum is 497. To get the average, divide by the array length: 497 ÷ 6 ≈ 82.83.
Min / Max: What Is the Highest Score?
We initialize let max = scores[0], which is 88. Starting from index 1: is 72 > 88? No. Is 95 > 88? Yes — max becomes 95. Is 63 > 95? No. Is 88 > 95? No. Is 91 > 95? No. The maximum score is 95. Notice that we start at scores[0] rather than 0 because if all scores were negative, starting at 0 would give a wrong answer. This is a common beginner mistake.
Searching: Is There a Score of Exactly 63?
We initialize let found = false. The loop checks: 88 === 63? No. 72 === 63? No. 95 === 63? No. 63 === 63? Yes — found becomes true. We could add a break statement here to exit the loop early since we already know the answer. Without break, the loop continues but the result stays true. Either approach is correct.
Common Pitfall
Infinity for min and -Infinity for max.SECTION 5
Code Templates — Copy-and-Adapt Patterns
Below is a reference table showing the JavaScript code template for each pattern. You can think of these as fill-in-the-blank recipes — swap in your own array name, condition, or target value, and the pattern works for any problem.
| Pattern | Initialize | Loop Body Update | After Loop |
|---|---|---|---|
| Counting | let count = 0; | if (condition) { count++; } | count holds the tally |
| Summing | let total = 0; | total += arr[i]; | total holds the sum |
| Max | let max = arr[0]; | if (arr[i] > max) { max = arr[i]; } | max holds the largest |
| Min | let min = arr[0]; | if (arr[i] < min) { min = arr[i]; } | min holds the smallest |
| Search (boolean) | let found = false; | if (arr[i] === target) { found = true; } | found is true or false |
| Search (index) | let idx = -1; | if (arr[i] === target) { idx = i; } | idx is position or −1 |
JavaScript loop pattern templates
SECTION 6
Worked Example — Combining Multiple Patterns
A teacher has an array of quiz scores and wants a program that reports: the number of passing scores (70 or above), the class average, and the highest score. This problem requires three loop patterns working together.
Quiz Score Analyzer
- 1
Step 1 — Set Up the Data
Start by declaring the array and all three accumulator variables. The counting variablepassCountstarts at 0, the summing variabletotalstarts at 0, and the max variablehigheststarts at the first element.let quizzes = [85, 62, 91, 74, 58, 97, 80];→let passCount = 0; let total = 0; let highest = quizzes[0]; - 2
Step 2 — Write a Single Loop That Handles All Three Patterns
You do not need three separate loops. A singleforloop can perform all three updates on each iteration. Inside the loop body: add the current score tototal(summing); check if the score is ≥ 70 and incrementpassCount(counting); and check if the score is greater thanhighestand replace it if so (max).for (let i = 0; i < quizzes.length; i++) { total += quizzes[i]; if (quizzes[i] >= 70) { passCount++; } if (quizzes[i] > highest) { highest = quizzes[i]; } } - 3
Step 3 — Trace Through the Array
Walking through each element: 85 → total = 85, passCount = 1, highest = 85. 62 → total = 147, passCount stays 1, highest stays 85. 91 → total = 238, passCount = 2, highest = 91. 74 → total = 312, passCount = 3, highest stays 91. 58 → total = 370, passCount stays 3, highest stays 91. 97 → total = 467, passCount = 4, highest = 97. 80 → total = 547, passCount = 5, highest stays 97.After the loop:passCount = 5,total = 547,highest = 97 - 4
Step 4 — Compute the Average and Display Results
The average istotal / quizzes.length, which is 547 ÷ 7 ≈ 78.14. Useconsole.log()to print the results.let average = total / quizzes.length;→ Passing: 5, Average: 78.14, Highest: 97
Pro Tip
SECTION 7
Pattern Comparison — When to Use What
Each pattern has specific strengths and common use cases. Choosing the right pattern starts with asking yourself: what question am I trying to answer about this data? The table below helps you match your question to the correct pattern.
| Question You're Asking | Pattern | Key Detail |
|---|---|---|
| "How many items meet this condition?" | Counting | Always requires an if-statement inside the loop |
| "What is the total / average of these values?" | Summing | Divide by length after the loop for average |
| "Which item is the biggest / smallest?" | Min / Max | Initialize to first element, not to 0 |
| "Does this value exist?" or "Where is it?" | Searching | Can break early once found for efficiency |
| "Give me a report on multiple aspects" | Combined | Multiple accumulators in one loop body |
Pattern selection guide
KEY TAKEAWAY
SECTION 8
Connection to Advanced Techniques
The four loop patterns you have learned are the foundation for more advanced programming concepts. As you progress, you will discover that JavaScript provides built-in array methods that encapsulate these patterns in a single function call. Understanding the manual loop versions makes these higher-level tools much easier to learn.
| Manual Loop Pattern | Built-In Array Method | Example |
|---|---|---|
| Counting with for loop | .filter().length | arr.filter(x => x >= 70).length |
| Summing with for loop | .reduce() | arr.reduce((sum, x) => sum + x, 0) |
| Min / Max with for loop | Math.max(...arr) | Math.max(...arr) |
| Searching with for loop | .includes() / .indexOf() / .find() | arr.includes(63) |
From manual loops to built-in methods
The key insight is that every built-in method is running a loop under the hood. When you call arr.reduce(), JavaScript is internally performing the same summing pattern you wrote manually. Knowing the manual version means you can debug problems, write custom variations, and understand performance trade-offs. In later courses, you will also encounter concepts like nested loops (loops inside loops) for processing 2D arrays, and sorting algorithms that combine counting and swapping patterns in creative ways.
SECTION 9
Practice Problems
Question 1: CONCEPTUAL
let max = 0; instead of let max = arr[0];. The array is [-3, -7, -1, -5]. What value will max hold after the loop, and why is it wrong?Show answer
max will remain 0 because none of the array values (−3, −7, −1, −5) are greater than 0. The correct maximum is −1, which is the largest negative number in the array. This illustrates why you should always initialize your min/max tracker to the first element of the array: it guarantees the starting value is actually in the dataset. Alternatively, you could use -Infinity as the initial value, since every real number is greater than negative infinity.Question 2: BASIC CALCULATION
let temps = [72, 68, 75, 80, 65];, write a JavaScript loop that calculates the sum of all temperatures and then computes the average. What values do total and average hold at the end?Show answer
let total = 0;. Loop: for (let i = 0; i < temps.length; i++) { total += temps[i]; }. After the loop, total = 72 + 68 + 75 + 80 + 65 = 360. Then let average = total / temps.length; gives 360 ÷ 5 = 72. The sum is 360 and the average is 72. This is the standard summing pattern with an extra division step after the loop to compute the average.Question 3: INTERMEDIATE
let words = ["apple", "banana", "cherry", "avocado", "apricot"];, write a loop that counts how many words start with the letter "a". Hint: use words[i][0] or words[i].startsWith("a") to check the first character.Show answer
let count = 0;. Loop: for (let i = 0; i < words.length; i++) { if (words[i].startsWith("a")) { count++; } }. Walking through the array: "apple" starts with "a" → count = 1. "banana" does not → count stays 1. "cherry" does not → count stays 1. "avocado" starts with "a" → count = 2. "apricot" starts with "a" → count = 3. The final value of count is 3. This is the counting pattern where the condition checks a string property rather than a numeric comparison.Question 4: APPLIED
let revenue = [1200, 980, 1450, 1100, 870, 1530, 1340];. Write a program that finds the minimum daily revenue and also determines whether any day exceeded $1500. Use two separate pattern variables in a single loop.Show answer
let minRev = revenue[0]; let exceeded = false;. Loop: for (let i = 0; i < revenue.length; i++) { if (revenue[i] < minRev) { minRev = revenue[i]; } if (revenue[i] > 1500) { exceeded = true; } }. Tracing through: 1200 is less than 1200? No. 980 < 1200? Yes → minRev = 980. 1450 < 980? No. 1100 < 980? No. 870 < 980? Yes → minRev = 870. 1530 < 870? No, but 1530 > 1500? Yes → exceeded = true. 1340 < 870? No. Final results: minRev = 870 and exceeded = true. This combines the min pattern and the search pattern in one loop.Question 5: CRITICAL THINKING
grades.length - 1 to get the adjusted average. Test with let grades = [90, 78, 95, 60, 88];.Show answer
let total = 0; let min = grades[0];. Loop: for (let i = 0; i < grades.length; i++) { total += grades[i]; if (grades[i] < min) { min = grades[i]; } }. After the loop: total = 90 + 78 + 95 + 60 + 88 = 411, and min = 60. Adjusted total = 411 − 60 = 351. Adjusted average = 351 ÷ (5 − 1) = 351 ÷ 4 = 87.75. The key insight is that you can combine patterns and then do additional arithmetic after the loop. This approach processes the array only once but answers a more complex question. In real-world grading systems, dropping the lowest score is a common policy, and this pattern combination handles it elegantly.SUMMARY
Lesson Summary
Summary
Every data-processing task you encounter in introductory programming boils down to four standard loop patterns. The counting pattern initializes a counter to 0 and increments it each time a condition is true. The summing pattern initializes a total to 0 and adds each value to produce a running sum. The min/max pattern initializes a tracker to the first element and replaces it whenever a smaller or larger value is found. The searching pattern initializes a flag (boolean or index) and updates it when the target is located.
All four patterns follow the same three-phase blueprint: initialize before the loop, update inside the loop body, and use the result after the loop finishes. You can combine multiple patterns into a single loop for efficiency. These manual loop patterns are also the foundation for JavaScript's built-in array methods like .reduce(), .filter(), and .find(), which you will learn in future courses.