JavaScript Array reduce() Method Explained Clearly
Direct Answer & Overview
The JavaScript Array reduce() method executes a reducer callback function on each array element, passing the accumulated result from preceding calculations forward. It aggregates arrays into numbers, objects, lookups, or transformed collections.
JavaScript Source Code
const numbers = [10, 20, 30];
const total = numbers.reduce((sum, number) => sum + number, 0);
console.log(total);How does this JavaScript code work?
Array.prototype.reduce() processes an array from left to right, maintaining a persistent accumulator value across iterations. The reducer callback receives the accumulator and the current element, performs a calculation, and returns the updated accumulator for the next cycle. Always provide an explicit initial value as the second argument to reduce() to prevent runtime errors when executing on empty arrays.
What is the expected terminal output?
Executing this code in JS CodeLab produces the following stdout sequence in the developer console:
60Common mistakes to avoid
- !Omitting the initial value parameter, which causes reduce() to throw a TypeError on empty arrays and use index 0 as the initial accumulator.
- !Forgetting to return the updated accumulator from the callback, causing it to become undefined on subsequent iterations.
- !Using reduce() for simple transformations that could be written much more readably with map() or filter().
- !Accidentally mutating an object accumulator rather than returning it cleanly.
Frequently Asked Questions
Why should you always supply an initial value to Array reduce()?
Supplying an initial value guarantees the accumulator starts with a predictable data type and prevents a runtime TypeError if the method is called on an empty array.
Can Array reduce() return an object instead of a number?
Yes. The accumulator can be any data type, including an object, an array, or a Map. This makes reduce() ideal for grouping, frequency counting, and flattening data.
When should you use reduce() instead of map() and filter()?
Use reduce() when you need to transform an array into a single aggregated value (like a sum, average, or dictionary). If transforming items 1:1, prefer map().
Comprehensive Tutorial
Want an in-depth understanding of this topic?
Read our complete, interactive tutorial covering memory management, edge cases, and best practices.
Read the full array reduce tutorial →