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.
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.
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.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.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.
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.
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.+= operator is shorthand for total = total + arr[i]. After the loop finishes, total contains the sum of all elements.count only increments when the condition inside the if statement is true. This lets you count how many elements meet a specific criterion.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.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 |
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.
let grades = [85, 62, 91, 47, 73, 68, 95];. The array has 7 elements, so grades.length is 7.7let passingCount = 0; before the loop. It starts at zero because we haven't checked any scores yet.passingCount = 0for (let i = 0; i < grades.length; i++). This ensures i takes values 0 through 6, visiting every element exactly once.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).passingCount holds 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);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 |
for...of or .forEach()) with confidence, just like switching to automatic after mastering manual.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) |
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."
Practice Problems
let total = 0; inside the loop body instead of before it?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?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.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.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?Lesson 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.