JavaScript AcademyProfessional Engineering
Level 2 · Core DevelopmentModule 7: Functional Array ProcessingLesson 34 of 150About 45 minutes

Lesson 34: reduce and aggregation

01Opening question

Total revenue, the most expensive item, a count per category: each turns a whole list into one answer. Is there one method for all of them?

Keep the question in mind. By the end of the lesson you will be able to answer it, and prove it with working code.

02Start with working code

reduce carries an accumulator (sum) from one call to the next. 0 is its starting value.

const prices = [4, 10, 6];
const total = prices.reduce((sum, p) => sum + p, 0);
console.log(total);

03Objective and prerequisites

Learning objective: Use reduce to combine a list into one value, always provide an initial value, build totals, maximums, counts and grouped objects, and read a reduce call step by step.

You need: Lesson 32: map and transformations, Lesson 33: filter and selection

Skills practised: Functional array processing, Aggregating with reduce.

04Explanation

list.reduce((acc, item) => newAcc, initial) walks through the list carrying an accumulator. Each call returns the next accumulator; the last one is the result.

Always pass the initial value (the second argument), such as 0 for a sum, "" for text or {} for an object.

Trace it: for [4, 10, 6] with initial 0, the calls are 0+4=4, 4+10=14, 14+6=20. The result is 20.

The callback must return the accumulator every time, even when nothing changes. Forgetting to return makes the next accumulator undefined.

05Definitions

reduce
Combines all elements into one value by repeatedly calling a function.
Accumulator
The running result passed from one reduce call to the next.
Initial value
The accumulator's starting value, passed as reduce's second argument.
Reducer
The function that takes the accumulator and one element and returns the new accumulator.
Aggregation
Combining many values into a summary such as a total, count or average.

Open the full glossary

06Visual learning object

Reduce accumulator explorer. Step through a reduce call and watch the accumulator change after every element.

Loading the interactive object…

Open the full Reduce accumulator explorer page with its guided experiment.

07Examples

ex-034-01Summing with reduce Browser-executable JavaScript

The accumulator starts at 0 and grows.

const sales = [120, 340, 90];
const total = sales.reduce((sum, s) => sum + s, 0);
console.log("Total:", total);
console.log("Average:", total / sales.length);
Sample input
None
Expected output
Total: 550 Average: 183.33333333333334
Common mistake
Leaving out the 0 initial value.
Try this
Round the average to 2 decimals.
Source
examples/ex-034-01-sum.js

ex-034-02Finding the maximum Browser-executable JavaScript

The accumulator keeps the best value seen so far.

const scores = [72, 95, 88];
const best = scores.reduce((max, s) => (s > max ? s : max), scores[0]);
console.log(best);
console.log(Math.max(...scores));
Sample input
None
Expected output
95 95
Common mistake
Starting the maximum at 0 when values can be negative.
Try this
Find the lowest score.
Source
examples/ex-034-02-max.js

ex-034-03Counting per category Browser-executable JavaScript

The accumulator is an object of counts.

const orders = ["tea", "coffee", "tea", "tea"];
const counts = orders.reduce((acc, drink) => {
  acc[drink] = (acc[drink] || 0) + 1;
  return acc;
}, {});
console.log(counts);
Sample input
None
Expected output
{tea: 3, coffee: 1}
Common mistake
Forgetting return acc, which makes acc undefined on the next call.
Try this
Count the letters in "banana".
Source
examples/ex-034-03-count-by.js

ex-034-04Totals per group Browser-executable JavaScript

Grouping and summing in one pass.

const expenses = [
  { cat: "food", amount: 12 },
  { cat: "travel", amount: 30 },
  { cat: "food", amount: 8 }
];
const byCat = expenses.reduce((acc, e) => {
  acc[e.cat] = (acc[e.cat] || 0) + e.amount;
  return acc;
}, {});
console.log(byCat.food, byCat.travel);
Sample input
None
Expected output
20 30
Common mistake
Using an array as the initial value when you need keys.
Try this
Add an "other" category.
Source
examples/ex-034-04-group-total.js

08Guided exercises

Three exercises: explore and modify, complete the implementation, then build independently. Tests check behaviour, so any correct solution passes.

Return the accumulator

Fix a reducer that does not return.

const cart = [2.5, 4, 1.5];
const total = cart.reduce((sum, price) => {
  sum + price;
}, 0);
console.log("Total:", total);

Cart total from objects

Reduce an array of objects to a number.

const cart = [
  { item: "Pen", qty: 4, price: 1.25 },
  { item: "Pad", qty: 2, price: 3.5 }
];
// TODO: reduce to the total cost

Group tasks by owner

Reduce to an object of arrays.

const tasks = [
  { title: "Design", owner: "Ada" },
  { title: "Build", owner: "Linus" },
  { title: "Test", owner: "Ada" },
  { title: "Ship", owner: "Grace" }
];

09Prediction

Commit to an answer first, then run the real code to compare.

const r = [1, 2, 3].reduce((acc, n) => acc + n, "");
console.log(r, typeof r);

What is printed?

10Debugging investigation

The average rating is far too high

Reviews of 4, 5 and 3 stars should average 4, but the product page shows 5.33.

const reviews = [{ stars: 4 }, { stars: 5 }, { stars: 3 }];
const sum = reviews.reduce((acc, r) => acc + r.stars, reviews.length);
const average = sum / reviews.length;
console.log(`Average: ${average.toFixed(2)}`);

More cases in the Debugging Detective Laboratory

11Practical scenario

Monthly spending dashboard

A budgeting app reduces a month of transactions into totals per category for a chart, plus one grand total, in a single pass over the data.

const tx = [{ c: "food", a: 40 }, { c: "rent", a: 900 }, { c: "food", a: 25 }];
const sums = tx.reduce((acc, t) => { acc[t.c] = (acc[t.c] || 0) + t.a; return acc; }, {});
console.log(sums);

12Knowledge check

1. What is printed?

console.log([1, 2, 3, 4].reduce((a, b) => a + b, 0));
  • 10
  • 1234
  • 4
  • undefined

2. What is the second argument of reduce?

  • The index
  • The initial value of the accumulator
  • The array
  • A compare function

3. What happens?

console.log([].reduce((a, b) => a + b));
  • Prints 0
  • Prints undefined
  • TypeError: Reduce of empty array with no initial value
  • Prints []

4. Why is counts undefined after the second element?

const counts = list.reduce((acc, x) => { acc[x] = (acc[x] || 0) + 1; }, {});
  • {} is wrong
  • The reducer does not return acc
  • += cannot be used
  • reduce cannot build objects

5. In reduce((acc, x) => acc + x, 10) over [1, 2], what is acc in the second call?

  • 10
  • 11
  • 13
  • 2

6. A reduce callback has grown to 15 lines. What is a good next step?

  • Make it one line
  • Extract a named reducer or use a plain loop
  • Remove the initial value
  • Use map instead

13Solutions and tests

Each exercise's solution appears in the exercise once you have run its tests. Solutions are one possible answer: the tests accept any implementation with the same behaviour.

Automated acceptance tests for this lesson

These are the same checks the exercises run. They are visible on purpose: client-side tests help you learn and are not secret.

  • Return the accumulator: Prints Total: 8
  • Cart total from objects: Prints the total; Uses reduce
  • Group tasks by owner: Prints the groups; groupBy returns arrays; Uses reduce
  • ex-034-01: output matches the documented expected output
  • ex-034-02: output matches the documented expected output
  • ex-034-03: output matches the documented expected output
  • ex-034-04: output matches the documented expected output

Download the whole lesson folder (examples, exercises, solutions, tests) as ZIP

14Source files

The lesson lives in the companion repository at curriculum/level-02-core-development/module-07-functional-array-processing/lesson-034-reduce-and-aggregation/. Every example on this page is generated from those files.

These links open the files in the GitHub repository (https://github.com/lsvekis/JavaScript-Professional-Engineering-Academy). You can also use the ZIP download above.

15Summary and next steps

  • reduce combines a list into one value with an accumulator.
  • Always pass an initial value.
  • The reducer must return the accumulator every time.
  • Use reduce for totals, maximums, counts and groups.

16AI learning prompts

Copy a prompt into the AI assistant of your choice. Then verify what it says by running code here. No AI service is connected to this page.

Concept explanation reduce
Context: I am learning reduce in JavaScript.
Task: Explain reduce with a step-by-step table of the accumulator for a sum, a maximum and a count.
Constraints: Beginner-friendly language, short runnable examples, no libraries.
Expected behaviour: I can explain the idea in my own words and predict small programs.
Testing: Finish with three quick questions for me to answer.
Code prediction reduce drill
Context: I have practised reduce.
Task: Give me six reduce calls and ask for their results, including different initial values.
Constraints: Wait for my answer before revealing each result.
Expected behaviour: Each question has exactly one correct output.
Testing: Explain any I miss with a step-by-step trace.
Debugging reduce bug
Context: My reduce result is undefined or NaN.
Task: Help me find the cause with questions instead of giving me the fix.
Constraints: Do not rewrite my program.
Expected behaviour: I locate and fix the bug myself.
Testing: Suggest the console.log lines that would reveal the problem.
Exercise generation reduce practice
Context: I finished the reduce exercises.
Task: Create three reduce exercises: a total, a group-by and a count.
Constraints: Fictional data and exact expected output.
Expected behaviour: Each exercise has tests I can run.
Testing: Put the solutions in a separate hidden section.
Code review reduce review
Context: Here is my code that uses reduce.
Task: Review my reduce calls for missing initial values, missing returns and readability.
Constraints: Explain each suggestion briefly and keep behaviour identical.
Expected behaviour: The code is clearer and has no hidden mutation or edge-case bug.
Testing: List the changes in order of importance.