Master Code
On The Go

Learn. Practice. Build.

Home › Code Snippets › JavaScript › Reference › reduce()

JavaScript Reference

Array.prototype.reduce()

Combines all elements into a single value — a sum, an object, a string, or anything else.

Last updated: October 2026

reduce() collapses an array into a single value — a sum, an object, a string, anything. Use it when you need one result from many items.

Full definition: Array.prototype.reduce() executes a reducer function on each element, resulting in a single output value.

🎬 Live Example

Five common reduce patterns. Click any button to see the output.

Input:

                
Output:

            

💡 reduce can return anything. Don't be afraid to use it beyond sums.

📝

Basic Syntax

array.reduce(callback(accumulator, currentValue, index, array), initialValue)

// Returns a single value

The callback runs once per element and returns the new accumulator value.

🎯 Syntax & Parameters

Parameter Type Description
callbackFunctionRuns for each element. Returns the new accumulator.
accumulatoranyThe value returned by the previous callback call.
currentValueanyThe current element being processed.
indexnumberIndex of the current element.
arrayArrayThe original array.
initialValueanyStarting value for the accumulator (optional but strongly recommended).
1

Sum and Product

const numbers = [1, 2, 3, 4, 5];

// Sum
const sum = numbers.reduce((acc, n) => acc + n, 0);
// 15

// Product
const product = numbers.reduce((acc, n) => acc * n, 1);
// 120

// Average
const avg = numbers.reduce((acc, n) => acc + n, 0) / numbers.length;
// 3

💡 Note: For simple sums you can also use for...of with an accumulator. reduce is best when you need to combine objects or complex structures.

2

Reduce to an Object

const orders = [
    { customer: 'Alice', amount: 100 },
    { customer: 'Bob', amount: 200 },
    { customer: 'Alice', amount: 50 }
];

// Total per customer
const totals = orders.reduce((acc, order) => {
    acc[order.customer] = (acc[order.customer] || 0) + order.amount;
    return acc;
}, {});
// { Alice: 150, Bob: 200 }

This is reduce's superpower — it can build any data structure from an array.

3

Group by Property

const products = [
    { name: 'Apple', category: 'fruit' },
    { name: 'Carrot', category: 'veg' },
    { name: 'Banana', category: 'fruit' },
    { name: 'Broccoli', category: 'veg' }
];

const grouped = products.reduce((acc, product) => {
    const key = product.category;
    (acc[key] ||= []).push(product);
    return acc;
}, {});
// {
//   fruit: [Apple, Banana],
//   veg: [Carrot, Broccoli]
// }

The ||= logical assignment initializes the array only if it doesn't exist yet.

4

Max, Min, Deduplicate

const numbers = [3, 7, 2, 9, 1, 8];

// Max
const max = numbers.reduce((a, b) => Math.max(a, b));
// 9

// Min
const min = numbers.reduce((a, b) => Math.min(a, b));
// 1

// Deduplicate
const unique = numbers.reduce((acc, n) => {
    if (!acc.includes(n)) acc.push(n);
    return acc;
}, []);
5

Reduce with an Initial Value

Always provide an initial value. Here's why:

// Without initial value — throws on empty array
[].reduce((a, b) => a + b);
// ❌ TypeError: Reduce of empty array with no initial value

// With initial value — works on empty array
[].reduce((a, b) => a + b, 0);
// ✅ 0

// On single-element array
[5].reduce((a, b) => a + b);
// 5 (uses the element as the accumulator)

[5].reduce((a, b) => a + b, 10);
// 15 (uses 10 as the accumulator)

Rule: Always pass an initial value. It makes your code predictable and works on empty arrays.

🎯 reduce vs map vs filter

Method Returns Use when
mapNew array, same lengthTransform each element
filterNew array, subsetKeep matching elements
reduceSingle value (any type)Combine all into one result

You can replace map + filter with reduce, but the code is usually less readable. Use the right tool for the job.

⚠️ Common Mistakes

❓ Frequently Asked Questions

What does Array.reduce() do in JavaScript?

Array.reduce() combines all elements of an array into a single value using a reducer callback. It accepts an accumulator and a current value, returning the final accumulated result. It can produce numbers, strings, objects, or arrays.

What is the initial value in reduce()?

The initial value is the starting value for the accumulator on the first iteration. If omitted, reduce uses the first element of the array as the initial accumulator and starts iterating from the second element.

Why should I always pass an initial value to reduce()?

Passing an initial value prevents errors on empty arrays (which would throw TypeError without one) and makes the code clearer. It is a widely recommended best practice.

What is the difference between reduce and map?

map transforms each element and returns a new array of the same length. reduce combines all elements into a single value — a sum, an object, a string, or anything else.

Can reduce() return an object?

Yes. reduce can return anything. A common pattern is to reduce an array of items into an object keyed by a specific property — like grouping orders by customer ID or counting occurrences.

🎯 What's Next?

← All JavaScript Reference