Computer Programming 1 (JavaScript) • Core Data Structures

Iterating Arrays — I can iterate over arrays to compute results (totals, counts) using for loops at my level.

Learn to traverse every element in an array and accumulate totals, counts, and other computed results using JavaScript for loops.

A JavaScript data file with code brackets and a laptop.
Inside this lesson 10 sections 5 questions 8 figures

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

John von Neumann describes a computer architecture where instructions are stored in memory, enabling repeating loops that process data sequences automatically.

1957 • FORTRAN's DO Loop

IBM releases FORTRAN, the first widely used high-level language. Its DO loop lets programmers iterate over arrays of numbers to compute scientific results — a pattern still used today.

1972 • C Language for Loop

Dennis Ritchie creates C at Bell Labs. Its for loop syntax (initialization; condition; update) becomes the template that JavaScript and many other modern languages adopt.

1995 • JavaScript Is Born

Brendan Eich creates JavaScript in 10 days at Netscape. It inherits C-style for loops, making array iteration familiar to millions of developers who later build the modern web.

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.

1

Array

An ordered list of values stored under a single variable name. Each value sits at a numbered position starting from 0. Example: let scores = [88, 92, 75, 100];
2

Index

The numeric position of an element within an array. The first element has index 0, the second has index 1, and so on. Access an element with bracket notation: scores[2] returns 75.
3

For Loop

A control structure with three parts — initialization, condition, and update — that repeats a block of code a specific number of times: for (let i = 0; i < arr.length; i++).
4

Accumulator

A variable declared before the loop that gathers results as the loop runs. For summing, you start it at 0 and add each element. For counting, you start at 0 and increment when a condition is met.
✦

KEY TAKEAWAY

Think of iterating an array like walking down a hallway of lockers. Each locker (element) has a number on it (the index). You start at locker 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.

For Loop Iteration — Summing an Arraylet scores = [88, 92, 75, 100];let total = 0;Index 088Index 192Index 275Index 3100Pass 1: i = 0total = 0 + 88 = 88Pass 2: i = 1total = 88 + 92 = 180Pass 3: i = 2total = 180 + 75 = 255Pass 4: i = 3total = 255 + 100 = 355Final total = 355
Each colored box represents one pass through the loop. The index 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

for(initialization;condition;update)bodyfor (initialization; condition; update) { body }

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

lettotal=0;for(leti=0;i<arr.length;i++)total+=arr[i];let total = 0; for (let i = 0; i < arr.length; i++) { total += arr[i]; }

The += operator is shorthand for total = total + arr[i]. After the loop finishes, total contains the sum of all elements.

COUNTING PATTERN

letcount=0;for(leti=0;i<arr.length;i++)if(arr[i]>=80)count++;let count = 0; for (let i = 0; i < arr.length; i++) { if (arr[i] >= 80) { count++; } }

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

Arrays are zero-indexed, so the last valid index is 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.

Four Accumulator Patterns on [10, 25, 15, 30, 20]1. Sum (Total)let total = 0;for (let i = 0; i < arr.length; i++) { total += arr[i];}total → 100(10+25+15+30+20)2. Count (Conditional)let count = 0;for (let i = 0; i < arr.length; i++) { if (arr[i] >= 20) count++;}count → 3(25, 30, 20)3. Averagelet total = 0;for (let i = 0; i < arr.length; i++) { total += arr[i];}let avg = total / arr.length;avg → 20(100 ÷ 5)4. Find Maximumlet max = arr[0];for (let i = 1; i < arr.length; i++) { if (arr[i] > max) max = arr[i];}max → 30(largest value)
All four patterns use the same for loop structure. The key differences are (1) how the accumulator is initialized and (2) what operation is performed inside the loop body. Notice that the average pattern is really just the sum pattern followed by a division step after the loop, and the maximum pattern initializes max to the first element rather than 0, and starts i at 1.
PatternInit AccumulatorLoop Body ActionAfter Loop
Sumlet total = 0total += arr[i]Use total
Countlet count = 0if (condition) count++Use count
Averagelet total = 0total += arr[i]total / arr.length
Max / Minlet 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. 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, so grades.length is 7.
    Array length: 7
  2. 2

    Step 2 — Initialize the Accumulator

    Since we are counting, we create a variable let passingCount = 0; before the loop. It starts at zero because we haven't checked any scores yet.
    passingCount = 0
  3. 3

    Step 3 — Write the For Loop

    We set up the loop: for (let i = 0; i < grades.length; i++). This ensures i takes values 0 through 6, visiting every element exactly once.
  4. 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. 5

    Step 5 — Read the Result

    After the loop finishes, 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);
    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.

Featurefor loopfor...of loop.forEach() method
Access to index?Yes — i is the indexNot directly (extra steps needed)Yes — passed as second argument
Control over start/stop?Full control — customize init, condition, updateAlways visits every elementAlways visits every element
Can use break?YesYesNo — cannot break out early
ReadabilityMore verbose but very clearConcise and cleanConcise, functional style
Best for beginners?Yes — teaches how iteration worksGood once basics are solidRequires understanding callbacks

Comparing three array iteration approaches in JavaScript

🔑

WHY START WITH FOR LOOPS?

The traditional for loop is like learning to drive a manual-transmission car. It's more work, but you understand exactly how the engine, clutch, and gears work together. Once you master the mechanics of initialization, condition-checking, and incrementing, you can switch to more automated approaches (like 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 NowWhat 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 loopThe .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 timeNested 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

Explain in your own words why the accumulator variable must be declared and initialized before the for loop, not inside it. What would happen if you wrote let total = 0; inside the loop body instead of before it?
Show answer
If the accumulator is declared inside the loop body, it gets reset to 0 on every pass. Each iteration would overwrite the previous result, so after the loop you'd only have the last element's value added to 0 rather than the sum of all elements. By declaring it before the loop, the variable persists across all iterations, letting each pass build on the work of previous passes. This is the essential idea of accumulation — the variable must survive from one iteration to the next.

Question 2: BASIC CALCULATION

Given 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
The code is: 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

Given 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
You can use two accumulators in one loop: 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

A small online store tracks daily sales in an array: 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
The code is: 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

Consider the array 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
This is a classic problem solved by Kadane's algorithm. The idea is to track the best sum ending at each position: 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.

Varsity Tutors • Computer Programming 1 (JavaScript) • Iterating Arrays — I can iterate over arrays to compute results (totals, counts) using for loops at my level.