COMPUTER PROGRAMMING 1 (JAVASCRIPT) • CONDITIONALS, LOOPS & COMMON PATTERNS

Loop Patterns — I can use standard loop patterns (counting, summing, min/max, searching) to solve problems at my level.

Master the four essential loop recipes that every programmer uses to process data efficiently.

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
Ada Lovelace wrote the first published computer algorithm for Charles Babbage's Analytical Engine. Her notes describe a loop to compute Bernoulli numbers — the earliest known use of a repeating instruction pattern.
1945
Von Neumann Architecture
John von Neumann introduced the stored-program concept, allowing a computer to jump back to earlier instructions. This "branch" capability made loops a fundamental hardware feature, not just a theoretical idea.
1957
FORTRAN's DO Loop
The FORTRAN language introduced the DO loop, giving programmers a clean, readable way to repeat blocks of code. Patterns like summing arrays became standard practice in scientific computing.
1995
JavaScript Is Born
Brendan Eich created JavaScript in just ten days. It inherited C-style for loops and while loops, carrying forward decades of loop-pattern wisdom into the language of the web.

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.

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.

1

Counting Pattern

Initialize a counter to 0. Each time an item meets a condition inside the loop, increment the counter by 1. After the loop, the counter holds the total number of matching items.
2

Summing Pattern

Initialize a total to 0. On each iteration, add the current value to the running total. After the loop, the variable holds the sum of all processed values.
3

Min / Max Pattern

Initialize a tracker to the first element (or to Infinity / −Infinity). On each iteration, compare the current element to the tracker and replace it if the current element is smaller (min) or larger (max).
4

Searching Pattern

Initialize a result variable (often a boolean set to false, or an index set to −1). Loop through the data, and when the target is found, update the result and optionally break out of the loop early.
✦ KEY TAKEAWAY
Think of loop patterns like a cashier scanning groceries. The counting pattern is like tallying how many produce items go by. The summing pattern is the running total displayed on the register. The min/max pattern is noticing the cheapest or most expensive item. And the searching pattern is scanning the belt looking for a specific coupon item. The cashier always starts fresh (initialize), handles each item one at a time (update), and reads the final display when done (use).

Visual Explanation — The Loop Pattern Blueprint

Every loop pattern follows the same three-phase structure: initialize a result variable, update it inside the loop body, and use the result after the loop completes. The four cards at the bottom show how each specific pattern fills in that 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.

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
When finding a minimum or maximum, never initialize your tracker to 0. If all values in the array are negative (for max) or all are positive and large (for min), starting at 0 will give a wrong result. Always initialize to the first element of the array, or use Infinity for min and -Infinity for max.

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.

JavaScript loop pattern templates
PatternInitializeLoop Body UpdateAfter Loop
Countinglet count = 0;if (condition) { count++; }count holds the tally
Summinglet total = 0;total += arr[i];total holds the sum
Maxlet max = arr[0];if (arr[i] > max) { max = arr[i]; }max holds the largest
Minlet 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
This trace table shows how the summing pattern accumulates a running total. Each row represents one iteration of the loop. The "total after" column feeds into the "total before" column of the next row.

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 DataStart by declaring the array and all three accumulator variables. The counting variable passCount starts at 0, the summing variable total starts at 0, and the max variable highest starts 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 PatternsYou do not need three separate loops. A single for loop can perform all three updates on each iteration. Inside the loop body: add the current score to total (summing); check if the score is ≥ 70 and increment passCount (counting); and check if the score is greater than highest and 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 ArrayWalking 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 ResultsThe average is total / quizzes.length, which is 547 ÷ 7 ≈ 78.14. Use console.log() to print the results.
let average = total / quizzes.length; → Passing: 5, Average: 78.14, Highest: 97
💡 Pro Tip
Combining multiple patterns into one loop is more efficient than writing separate loops. The computer only has to walk through the array once instead of three times. This efficiency matters when arrays contain thousands or millions of elements.

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.

Pattern selection guide
Question You're AskingPatternKey Detail
"How many items meet this condition?"CountingAlways requires an if-statement inside the loop
"What is the total / average of these values?"SummingDivide by length after the loop for average
"Which item is the biggest / smallest?"Min / MaxInitialize to first element, not to 0
"Does this value exist?" or "Where is it?"SearchingCan break early once found for efficiency
"Give me a report on multiple aspects"CombinedMultiple accumulators in one loop body
✦ KEY TAKEAWAY
Think of choosing a loop pattern like picking the right kitchen tool. You would not use a blender to slice bread, and you would not use a knife to mix a smoothie. Similarly, if you need a total, reach for the summing pattern, not the counting pattern. The question you are trying to answer determines which pattern you use. Once you know the four basic tools, most data-processing tasks become routine.

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.

From manual loops to built-in methods
Manual Loop PatternBuilt-In Array MethodExample
Counting with for loop.filter().lengtharr.filter(x => x >= 70).length
Summing with for loop.reduce()arr.reduce((sum, x) => sum + x, 0)
Min / Max with for loopMath.max(...arr)Math.max(...arr)
Searching with for loop.includes() / .indexOf() / .find()arr.includes(63)

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.

Practice Problems

PROBLEM 1 — CONCEPTUAL
A student writes a max-finding loop but initializes 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?
PROBLEM 2 — BASIC CALCULATION
Given 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?
PROBLEM 3 — INTERMEDIATE
Given 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.
PROBLEM 4 — APPLIED
A store tracks daily revenue in an array: 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.
PROBLEM 5 — CRITICAL THINKING
A teacher stores grades in an array but wants to compute the average after dropping the lowest score. Write a program that uses the summing and min patterns to: (1) find the total of all grades, (2) find the minimum grade, (3) subtract the minimum from the total, and (4) divide by grades.length - 1 to get the adjusted average. Test with let grades = [90, 78, 95, 60, 88];.

Lesson 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.

Varsity Tutors • Computer Programming 1 (JavaScript) • Loop Patterns