For loops & accumulators
Repeat with a purpose
Lesson 5 of 20 · 9 min · Module 2: Decisions & reusable work
A loop repeats work while a condition remains true. An accumulator keeps a running result across those repetitions.
Start this lesson →Free. No installation: you write and run the code in your browser, and it is checked automatically.
By the end, you’ll be able to…
- Trace each part of a for loop
- Accumulate a result across iterations
- Avoid off-by-one errors
The idea
A for loop has an initializer, a condition, and an update. The body runs only while the condition is true. Start a sum at zero so the first addition has a sensible starting value.
let total = 0;
for (let i = 1; i <= 3; i++) {
total += i;
}
console.log(total); // 6
01Trace a small input
For n = 3, i takes the values 1, 2, and 3. total changes from 0 to 1, then 3, then 6. Once i becomes 4, the condition fails and the loop stops.
02Return after the work is done
A return statement exits the entire function. Place it after the loop to include every iteration. If n is zero, the body never runs and the initial total is still correct.
Your turn
sumTo(n) to return the sum of whole numbers from 1 through n, including n. The input is a nonnegative whole number; sumTo(0) must return 0.What the checks look for
- Includes every value through five
- Handles an empty range
- Handles one and a larger range
Take this with you
A correct loop needs a starting state, a stopping rule, and an update that moves toward the stopping rule.