JavaScript Accumulator Patterns: Totals and Counts
Quick answer
An accumulator holds the partial result of a repeated operation. Initialize it before the loop and update it with each relevant item or iteration.
How it works
For summation, start from 0, the additive identity. For multiplication, start from 1. A count starts from 0 and increments only when its condition holds. Resetting the accumulator inside the loop discards earlier contributions. Inputs with no iterations still return the initial value.
let sum = 0;for (let n = 1; n <= 4; n++) { sum += n; }console.log(sum);Expected output in Node.js:
10The partial sum grows by each successive number.
let product = 1;let count = 0;for (let n = 1; n <= 6; n++) { if (n % 2 === 0) { product *= n; count++; } }console.log(product, count);Expected output in Node.js:
48 3Only 2, 4 and 6 contribute.
Common mistakes
Initializing a product to zero forces it to stay zero for finite factors. Choose a starting value that represents an empty computation.
Practice
Calculate the product of integers from 1 through n, with empty product 1.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
JavaScript Accumulator Patterns: Totals and Counts — Knowledge Check
Apply the taught concept and reason about the result.
Which initial value represents an empty sum?
Which initial value represents an empty product?
Why initialize an accumulator outside the loop?
What product results from multiplying 2, 4 and 6 starting at 1?
What should a count accumulator do when an item fails its condition?