SECTION 1
Historical Context & Motivation
Before computers existed, humans needed to process lists of data by hand. Imagine a bank clerk in the 1940s adding up hundreds of account balances with a pencil — slow, tedious, and error-prone. The invention of electronic computers promised to automate exactly this kind of repetitive work: visiting every item in a collection, one by one, and doing something useful with it. This core idea — iteration — became one of the most fundamental operations in all of programming.
1945 • Stored-Program Concept
1957 • FORTRAN's DO Loop
1972 • C Language for Loop
1995 • JavaScript Is Born
The central question this lesson addresses is straightforward: how do you visit every element in an array and combine those values into a single useful result? Whether you need a sum of test scores, a count of passing grades, or the average price in a shopping cart, the for loop gives you a reliable, step-by-step mechanism to get the job done.
SECTION 2
Core Principles & Definitions
Before writing any code, you should understand four foundational ideas that make array iteration work. These concepts fit together like puzzle pieces: an array stores the data, an index locates each element, a for loop controls the traversal, and an accumulator collects the result.
Array
0. Example: let scores = [88, 92, 75, 100];Index
0, the second has index 1, and so on. Access an element with bracket notation: scores[2] returns 75.For Loop
for (let i = 0; i < arr.length; i++).Accumulator
0 and add each element. For counting, you start at 0 and increment when a condition is met.KEY TAKEAWAY
0, open it, read what's inside, jot a note on your clipboard (the accumulator), then move to the next locker. You keep going until you've checked every locker. The for loop is your walking instructions; the accumulator is your clipboard.SECTION 3
Visual Explanation — How a For Loop Traverses an Array
The diagram below shows a for loop iterating over a four-element array to compute a total. Follow the colored arrow from top to bottom to see how the index variable i advances and how the accumulator total grows with each pass through the loop.
i starts at 0, accesses the element at that position, adds it to total, then increments. When i reaches scores.length (4), the loop stops and the final total is 355.Notice the pattern: before the loop, the accumulator total is initialized to 0. During each pass, the loop reads scores[i] and adds it to total. After all passes complete, total holds the sum of every element. This accumulator pattern is the backbone of almost every array iteration task.
SECTION 4
How the For Loop Works — Anatomy and Mechanics
A JavaScript for loop has three control expressions separated by semicolons inside the parentheses. Understanding each part is crucial to iterating arrays correctly.
FOR LOOP SYNTAX
Initialization: runs once before the loop starts (e.g., let i = 0). Condition: checked before every pass — the loop runs only while this is true (e.g., i < arr.length). Update: runs after each pass (e.g., i++). Body: the code executed each pass, where you access arr[i] and update the accumulator.
SUMMING PATTERN
The += operator is shorthand for total = total + arr[i]. After the loop finishes, total contains the sum of all elements.
COUNTING PATTERN
The accumulator count only increments when the condition inside the if statement is true. This lets you count how many elements meet a specific criterion.
Common Mistake: Off-by-One Errors
arr.length - 1. Always use i < arr.length (strictly less than), not i <= arr.length. Using <= will try to access one index past the end of the array, returning undefined and corrupting your result.SECTION 5
Common Iteration Patterns — Sum, Count, Average, and More
Once you understand the basic accumulator pattern, you can adapt it to solve many different problems. The diagram below shows four common patterns side by side, all operating on the same array of numbers. Each pattern differs only in how the accumulator is initialized and what happens inside the loop body.
max to the first element rather than 0, and starts i at 1.| Pattern | Init Accumulator | Loop Body Action | After Loop |
|---|---|---|---|
| Sum | let total = 0 | total += arr[i] | Use total |
| Count | let count = 0 | if (condition) count++ | Use count |
| Average | let total = 0 | total += arr[i] | total / arr.length |
| Max / Min | let max = arr[0] | if (arr[i] > max) max = arr[i] | Use max |
Quick reference for common accumulator patterns
SECTION 6
Worked Example — Counting Passing Grades
A teacher has an array of test scores and wants to know how many students scored 70 or above. Let's walk through the code step by step to count the passing grades.
Counting Scores ≥ 70
- 1
Step 1 — Define the Array
We start with an array of test scores:let grades = [85, 62, 91, 47, 73, 68, 95];. The array has 7 elements, sogrades.lengthis 7.Array length:7 - 2
Step 2 — Initialize the Accumulator
Since we are counting, we create a variablelet passingCount = 0;before the loop. It starts at zero because we haven't checked any scores yet.passingCount = 0 - 3
Step 3 — Write the For Loop
We set up the loop:for (let i = 0; i < grades.length; i++). This ensuresitakes values 0 through 6, visiting every element exactly once. - 4
Step 4 — Add the Conditional Logic
Inside the loop body, we check:if (grades[i] >= 70) { passingCount++; }. Only when the current score is 70 or higher does the counter go up. Let's trace each pass: i=0 → 85 ≥ 70 ✓ (count=1), i=1 → 62 < 70 ✗ (count=1), i=2 → 91 ≥ 70 ✓ (count=2), i=3 → 47 < 70 ✗ (count=2), i=4 → 73 ≥ 70 ✓ (count=3), i=5 → 68 < 70 ✗ (count=3), i=6 → 95 ≥ 70 ✓ (count=4). - 5
Step 5 — Read the Result
After the loop finishes,passingCountholds the value 4. The complete code is:let grades = [85, 62, 91, 47, 73, 68, 95]; let passingCount = 0; for (let i = 0; i < grades.length; i++) { if (grades[i] >= 70) { passingCount++; } } console.log(passingCount);passingCount = 4
SECTION 7
For Loops vs. Other Iteration Approaches
JavaScript offers several ways to iterate over arrays. The traditional for loop is the most explicit and flexible, but it helps to understand how it compares to alternatives you may encounter as you continue learning. The table below compares three common approaches.
| Feature | for loop | for...of loop | .forEach() method |
|---|---|---|---|
| Access to index? | Yes — i is the index | Not directly (extra steps needed) | Yes — passed as second argument |
| Control over start/stop? | Full control — customize init, condition, update | Always visits every element | Always visits every element |
| Can use break? | Yes | Yes | No — cannot break out early |
| Readability | More verbose but very clear | Concise and clean | Concise, functional style |
| Best for beginners? | Yes — teaches how iteration works | Good once basics are solid | Requires understanding callbacks |
Comparing three array iteration approaches in JavaScript
WHY START WITH FOR LOOPS?
for...of or .forEach()) with confidence, just like switching to automatic after mastering manual.SECTION 8
Connection to Advanced Concepts
The accumulator pattern you've learned is the foundation for some of the most powerful concepts in programming. As you advance, you'll discover that many built-in array methods are simply abstracted versions of the patterns you already know how to write by hand.
| What You Know Now | What You'll Learn Next |
|---|---|
Summing with a for loop and += | The .reduce() method — does the same thing in one line |
Counting with if inside a loop | The .filter() method — returns a new array of matching elements |
Accessing each element with arr[i] | The .map() method — transforms every element into a new array |
| Iterating one array at a time | Nested loops — iterating arrays within arrays (2D data, matrices) |
How today's skills connect to future topics
Every one of these advanced methods can be understood as a for loop with an accumulator under the hood. By mastering the explicit loop first, you build a mental model that makes higher-order functions feel natural rather than magical. When you later write arr.reduce((sum, val) => sum + val, 0), you'll think, "Oh, that's just my summing loop in a shorter form."
SECTION 9
Practice Problems
Question 1: CONCEPTUAL
let total = 0; inside the loop body instead of before it?Show answer
Question 2: BASIC CALCULATION
let prices = [4.99, 12.50, 7.25, 3.00, 8.75];, write a for loop that computes the total cost of all items. What is the final value of your accumulator?Show answer
let total = 0; for (let i = 0; i < prices.length; i++) { total += prices[i]; }. Tracing through: 0 + 4.99 = 4.99, then 4.99 + 12.50 = 17.49, then 17.49 + 7.25 = 24.74, then 24.74 + 3.00 = 27.74, then 27.74 + 8.75 = 36.49. The final value of total is 36.49. This uses the standard summing pattern with the accumulator initialized to 0.Question 3: INTERMEDIATE
let temps = [72, 68, 75, 80, 65, 71, 78]; (daily temperatures for a week), write code that computes both the average temperature and the number of days above 73°F. Use a single for loop to accomplish both tasks.Show answer
let total = 0; let hotDays = 0; for (let i = 0; i < temps.length; i++) { total += temps[i]; if (temps[i] > 73) { hotDays++; } } let avg = total / temps.length;. The total is 72 + 68 + 75 + 80 + 65 + 71 + 78 = 509. The average is 509 ÷ 7 ≈ 72.71. The days above 73 are 75, 80, and 78 — so hotDays equals 3. This problem shows that you can run multiple accumulator patterns simultaneously within a single loop, which is more efficient than looping twice.Question 4: APPLIED
let sales = [120, 0, 85, 200, 0, 150, 95];. Write a for loop that calculates the average revenue for only the days the store was open (days with sales greater than 0). Hint: you need to count open days separately.Show answer
let totalRevenue = 0; let openDays = 0; for (let i = 0; i < sales.length; i++) { if (sales[i] > 0) { totalRevenue += sales[i]; openDays++; } } let avgRevenue = totalRevenue / openDays;. The open-day sales are 120, 85, 200, 150, and 95, which sum to 650. There are 5 open days. The average revenue on open days is 650 ÷ 5 = 130. This demonstrates a conditional accumulation where both the sum and the count are filtered by the same condition, avoiding the mistake of dividing by the total array length (which would include zero-sale days and produce the wrong average of ≈92.86).Question 5: CRITICAL THINKING
let data = [3, -1, 4, -1, 5, -9, 2, 6];. Write a for loop that finds the largest sum you can get by adding any set of consecutive elements (this is sometimes called the maximum subarray sum). For example, the consecutive elements [3, -1, 4, -1, 5] sum to 10. Can you find a larger consecutive sum, or is 10 the maximum?Show answer
let maxSoFar = data[0]; let currentMax = data[0]; for (let i = 1; i < data.length; i++) { currentMax = Math.max(data[i], currentMax + data[i]); maxSoFar = Math.max(maxSoFar, currentMax); }. Tracing through: at index 1, currentMax = max(-1, 3 + (-1)) = 2; index 2 → max(4, 2+4) = 6; index 3 → max(-1, 6+(-1)) = 5; index 4 → max(5, 5+5) = 10; index 5 → max(-9, 10+(-9)) = 1; index 6 → max(2, 1+2) = 3; index 7 → max(6, 3+6) = 9. The maxSoFar tracks the largest currentMax seen, which is 10 (the subarray [3, -1, 4, -1, 5]). This problem demonstrates that the accumulator pattern can be extended with a decision at each step: either extend the current subarray or start fresh.SUMMARY
Lesson Summary
Summary
In this lesson, you learned that a for loop provides a structured way to visit every element in an array using an index variable that starts at 0 and increments until it reaches arr.length. The accumulator pattern — declaring a result variable before the loop, updating it inside the loop, and reading it after the loop — is the key technique for computing totals, counts, averages, and extremes.
You explored four common patterns (sum, count, average, and find max/min) and saw that they all share the same loop structure but differ in accumulator initialization and loop body logic. Remember to always use i < arr.length (not <=) to avoid off-by-one errors. These foundational skills prepare you for higher-order array methods like .reduce(), .filter(), and .map() that you will encounter in future lessons.