JavaScript Array reduce() Method

Beginner
⏱️ 9 min read
📚 Updated: Jul 2026
🎯 5 Examples
🚀 5 Try-it labs
Accumulate

What You’ll Learn

The reduce() method folds an array into a single value by running a callback on each element and carrying an accumulator forward. This tutorial covers syntax, initialValue, five examples (sum, max, flatten, object build, average), and comparisons with forEach and reduceRight.

01

Syntax

reduce(fn, init)

02

Accumulator

Carry state

03

initialValue

Start point

04

One result

Any type

05

Left → right

Order matters

06

ES5

Wide support

Introduction

Sometimes you do not want a new array—you want one number, one object, or one string built from many pieces. Summing prices, finding the maximum score, or merging nested lists are all reduce() jobs.

Think of the accumulator as a running total or bucket. Each step updates it; the final return is your answer. The source array is not modified.

Understanding the reduce() Method

array.reduce(callback, initialValue?) calls callback(accumulator, currentValue, index, array) for each element, left to right. Whatever you return becomes the accumulator for the next step.

If initialValue is provided, the first call uses it as the accumulator and starts at index 0. If omitted, the first element becomes the initial accumulator and iteration starts at index 1.

💡
Beginner Tip

Pass an initialValue (like 0 for sums or [] for building arrays) until you are comfortable with the no-initialValue rules—especially on empty arrays, which throw without one.

📝 Syntax

General form of Array.prototype.reduce:

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

Parameters

  • callback — returns the next accumulator value.
  • initialValue — optional starting accumulator (recommended for clarity).

Callback arguments

  • accumulator — running result so far.
  • currentValue — current element.
  • index — current position.
  • array — the array being reduced.

Return value

  • Final accumulator after the last element (any type).
  • Original array unchanged.

Common patterns

  • arr.reduce((a, n) => a + n, 0) — sum.
  • arr.reduce((max, n) => n > max ? n : max) — max (no init on non-empty).
  • arr.reduce((acc, x) => acc.concat(x), []) — flatten one level.
  • arr.reduce((obj, item) => ({ ...obj, [item]: true }), {}) — lookup object.

⚡ Quick Reference

GoalCode
Sum numbersarr.reduce((a, n) => a + n, 0)
Find maximumarr.reduce((m, n) => Math.max(m, n))
Flatten nested arraysnested.reduce((a, x) => a.concat(x), [])
Empty array + no initTypeError
Mutates array?No

📋 reduce() vs forEach() vs map() vs reduceRight()

Choose reduce when you need one combined result; use others for iteration or transformation.

reduce
one value

Left to right

forEach
undefined

Side effects

map
new array

1:1 transform

reduceRight
one value

Right to left

Examples Gallery

Open DevTools Console (F12) or use Try-it labs. Example N maps to ?tryit=N.

📚 Getting Started

Classic numeric reductions with initialValue.

Example 1 — Sum All Numbers

Start at 0 and add each element to the accumulator.

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

const sum = numbers.reduce((acc, num) => {
  return acc + num;
}, 0);

console.log(sum);
// 15
Try It Yourself

How It Works

Step by step: 0+1=1, 1+2=3, 3+3=6, 6+4=10, 10+5=15. The shorthand is numbers.reduce((a, n) => a + n, 0).

Example 2 — Find the Maximum Value

Without initialValue, the first element seeds the accumulator.

JavaScript
const scores = [88, 92, 76, 95, 84];

const max = scores.reduce((acc, score) => {
  return score > acc ? score : acc;
});

console.log(max);
// 95
Try It Yourself

How It Works

First call uses 88 as accumulator, compares with 92, then 95 wins. Or use Math.max(acc, score).

📈 Practical Patterns

Flatten, count, and compute averages.

Example 3 — Flatten a Nested Array (One Level)

Concatenate each inner array into an accumulator starting as [].

JavaScript
const nested = [[1, 2], [3, 4], [5, 6]];

const flat = nested.reduce((acc, chunk) => {
  return acc.concat(chunk);
}, []);

console.log(flat);
// [1, 2, 3, 4, 5, 6]
Try It Yourself

How It Works

Modern alternative: nested.flat(). Reduce teaches how accumulation builds a new array step by step.

Example 4 — Count Occurrences in an Object

Reduce can return objects, not just numbers.

JavaScript
const fruits = ["apple", "banana", "apple", "cherry", "banana", "apple"];

const counts = fruits.reduce((acc, fruit) => {
  acc[fruit] = (acc[fruit] || 0) + 1;
  return acc;
}, {});

console.log(counts);
// { apple: 3, banana: 2, cherry: 1 }
Try It Yourself

How It Works

Each fruit increments its key in the accumulator object. Always return acc so the next step sees updates.

Example 5 — Calculate an Average (Sum, Then Divide)

Sum with reduce, then divide by length—clearer than dividing inside the callback.

JavaScript
const numbers = [10, 20, 30, 40];

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

console.log(average);
// 25
Try It Yourself

How It Works

Sum is 100; divided by 4 elements gives 25. Guard against empty arrays before dividing.

🚀 Common Use Cases

  • Totals and stats — sum, product, min, max, average.
  • Grouping — build objects or Maps from arrays.
  • Flattening — merge nested arrays one level.
  • Pipeline composition — fold functions or values.
  • Single-pass transforms — filter + map in one loop (advanced).
  • Cart totals — sum price * qty across items.

🧠 How reduce() Runs

1

Set accumulator

Use initialValue or first element.

Start
2

Call callback

Pass acc, current value, index, array.

Step
3

Update accumulator

Return value becomes next acc.

Fold
4

Return final value

Last accumulator after all elements.

📝 Notes

  • Does not mutate the source array.
  • Always return the accumulator from your callback.
  • Empty array without initialValue throws TypeError.
  • Result type can be anything: number, string, object, array.
  • Order matters—use reduceRight for right-to-left.
  • Prefer readable loops when reduce hurts clarity.
  • ES5—excellent support including IE9+.

Browser & Runtime Support

Array.prototype.reduce() has been available since ES5 (2009). It is widely supported for accumulation and grouping patterns.

Baseline · ES5

Array.prototype.reduce()

Supported in Chrome 3+, Firefox 3+, Safari 4+, Edge (all versions), IE 9+, and all modern Node.js versions.

99% Universal support
Google Chrome Supported · Desktop & Mobile
Full support
Mozilla Firefox Supported · Desktop & Mobile
Full support
Apple Safari Supported · macOS & iOS
Full support
Microsoft Edge Supported · Chromium
Full support
Internet Explorer No native support · Use a polyfill
Polyfill
Opera Supported · Modern versions
Full support
Samsung Internet Supported · Android
Full support
Bun Supported · JavaScript runtime
Supported
Deno Supported · JavaScript runtime
Supported
Node.js Supported · Server runtime
Supported
Android WebView Supported · Modern WebView
Full support
Array.reduce() Excellent

Bottom line: Safe to use everywhere except very old IE8 environments. No polyfill needed for modern projects.

Conclusion

reduce() folds a list into one value by updating an accumulator at each step. Master sum and max first, then explore objects and flattening. Provide initialValue when it makes intent clear.

Next, learn reduceRight() to fold from the end toward the start.

💡 Best Practices

✅ Do

  • Pass initialValue for sums (0) and builds ([], {})
  • Always return the accumulator from the callback
  • Use descriptive names: acc, total, counts
  • Split complex logic: sum first, divide for average
  • Prefer flat() when flattening is the only goal

❌ Don’t

  • Forget to return inside the callback
  • Call reduce on empty arrays without initialValue
  • Force reduce when a simple loop reads better
  • Mutate the source array inside reduce unnecessarily
  • Assume reduce always returns a number

Key Takeaways

Knowledge Unlocked

Five things to remember about Array.reduce()

Fold many elements into one accumulated result.

5
Core concepts
📈 02

Accumulator

Running state.

Core
0 03

initialValue

Safe start.

Param
🎯 04

One result

Any type.

Output
05

Direction

Left to right.

Order

❓ Frequently Asked Questions

reduce() walks the array left to right, running a callback on each element. The callback returns an accumulator that carries forward; the final accumulator is the method's return value.
No. reduce() only reads the array. However, your callback can mutate objects you store in the accumulator if you choose to.
initialValue is the starting accumulator passed to the first callback call. Without it on an empty array, reduce throws TypeError. With mixed types, always provide one for predictable results.
callback(accumulator, currentValue, currentIndex, array). Return the next accumulator from each step.
forEach() returns undefined and is for side effects. reduce() returns one combined result built from all elements.
reduce() is ES5 (2009). It works in all modern browsers and has been supported in Internet Explorer 9+.
Did you know?

reduce() is so flexible that map and filter can be implemented with it—but in real code, use the dedicated methods unless you truly need a single custom pass.

Continue to reduceRight()

Learn how to accumulate values starting from the last element.

reduceRight() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful