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.
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.
Without an initial value reduce uses the first element as the accumulator and starts at the second, and an empty array throws TypeError: Reduce of empty array with no initial value.
Grouping with reduce (acc[key] ??= []; acc[key].push(x); return acc;) is idiomatic; Object.groupBy(list, fn) (ES2024) now does this directly where supported.
Mutating the accumulator object you created as the initial value is fine and fast; spreading a new object each step ({ ...acc, [k]: v }) is O(n²) for large inputs.
If a reduce becomes hard to read, a named reducer function or a plain loop is often clearer. Clarity beats cleverness.
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.
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
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.
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 explanationreduce
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 predictionreduce 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.
Debuggingreduce 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 generationreduce 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 reviewreduce 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.