1. Home
  2. Blog
  3. Software Development

Software Development

JavaScript Reduce Explained: 12 Practical Examples

JavaScript reduce turns an array into a single value: a total, an object, a map or even a chain of promises. Learn how the accumulator works step by step, the patterns worth knowing, the empty array error, and when a plain loop is the better choice, with output from real runs.

9 min read
JavaScript reduce explained: 12 practical examples

Key takeaways

  • JavaScript reduce calls your function once per element, carrying an accumulator from one call to the next.
  • Always pass an initial value. Without it, an empty array throws TypeError and arrays of objects give wrong results.
  • Mutating the accumulator is fine and fast. Spreading it into a new object every step was about 90 times slower in our test.
  • For simple grouping, Object.groupBy is now clearer than reduce.

map transforms every item and filter keeps some of them, but sometimes you need to boil a whole array down to one result: a cart total, a word count, an index by ID. That is the job of JavaScript reduce. It is the most flexible array method and also the most misunderstood, because the accumulator can be anything.

All examples were run on Node.js v24.22.1, and the output shown is what it printed. Need a refresher on the other array methods first? See our guide to JavaScript array methods.

What does reduce do in JavaScript?

Array.prototype.reduce() walks through an array from left to right. For each element it calls a reducer function with two main arguments: the value accumulated so far and the current element. Whatever the reducer returns becomes the accumulator for the next element. After the last element, reduce returns the final accumulator.

The result does not have to be a number. It can be a string, an array, an object, a Map or a promise. That is what makes reduce powerful, and also why it can become hard to read.

Reduce syntax

array.reduce((accumulator, currentValue, index, array) => {
  // return the new accumulator
}, initialValue);
  • accumulator: the running result.
  • currentValue: the element being processed.
  • index and array: optional, rarely needed.
  • initialValue: the starting accumulator. Optional in theory, but you should almost always provide it.

How reduce works, step by step

We logged every call while summing [1, 2, 3] from an initial value of 0:

[1, 2, 3].reduce((acc, n, i) => {
  console.log(`i=${i} acc=${acc} n=${n} -> ${acc + n}`);
  return acc + n;
}, 0);

// i=0 acc=0 n=1 -> 1
// i=1 acc=1 n=2 -> 3
// i=2 acc=3 n=3 -> 6

Each line shows the accumulator going in and the value coming out. The returned 6 is the final result. If you ever get lost in a complex reducer, adding this one log line is the fastest way to see what is happening.

Examples 1 to 3: sum, max and average

const nums = [4, 8, 15, 16, 23, 42];

nums.reduce((acc, n) => acc + n, 0);                    // 108
nums.reduce((m, n) => (n > m ? n : m));                 // 42
nums.reduce((acc, n, i, arr) => acc + n / arr.length, 0); // 18

Summing is the classic use. For a maximum, Math.max(...nums) is shorter, but it can throw a RangeError on very large arrays because of the argument limit, while reduce handles any size. The average example uses the fourth argument, the array itself, to divide as it goes.

Example 4: counting occurrences

const fruits = ["apple", "kiwi", "apple", "fig", "kiwi", "apple"];
const tally = fruits.reduce((t, f) => {
  t[f] = (t[f] ?? 0) + 1;
  return t;
}, {});
// { apple: 3, kiwi: 2, fig: 1 }

Start with an empty object and increment a key for each item. The ?? operator supplies 0 the first time a key appears. The same pattern counts words, status codes in a log file or votes in a poll.

Example 5: grouping objects

const orders = [
  { id: 1, city: "Pune",  total: 250 },
  { id: 2, city: "Delhi", total: 120 },
  { id: 3, city: "Pune",  total: 80 },
];

const byCity = orders.reduce((g, o) => {
  (g[o.city] ??= []).push(o.id);
  return g;
}, {});
// { Pune: [ 1, 3 ], Delhi: [ 2 ] }

Grouping used to be the top reason to reach for reduce. Modern JavaScript now has Object.groupBy(orders, o => o.city), which returned the same groups in our test (with full objects instead of IDs). Prefer it when your runtime supports it, and keep reduce for groupings that also aggregate.

Example 6: totals in a Map

const totals = orders.reduce(
  (m, o) => m.set(o.city, (m.get(o.city) ?? 0) + o.total),
  new Map()
);
console.log([...totals]);   // [ [ 'Pune', 330 ], [ 'Delhi', 120 ] ]

Map.prototype.set returns the map itself, which makes it a natural one-line reducer. A Map keeps insertion order and allows non-string keys; our Map vs Object guide explains when that matters.

Examples 7 and 8: flattening and indexing

[[1, 2], [3], [4, 5]].reduce((a, b) => a.concat(b), []);
// [ 1, 2, 3, 4, 5 ]

const byId = orders.reduce((idx, o) => { idx[o.id] = o.city; return idx; }, {});
// { '1': 'Pune', '2': 'Delhi', '3': 'Pune' }

Flattening with reduce works, but arr.flat() is clearer today. Building a lookup object by ID is still a great reduce job: turn an array into an object once, then look items up instantly instead of calling find in a loop. Note that object keys become strings.

Example 9: composing functions

const pipe = (...fns) => x => fns.reduce((v, f) => f(v), x);
const format = pipe(x => x + 1, x => x * 2, x => `#${x}`);
console.log(format(5));   // #12

Here the array holds functions, and the accumulator is the value passing through them: 5 becomes 6, then 12, then the string #12. This is how many middleware and data-pipeline helpers are built.

Example 10: running promises in sequence

const sleep = (ms, v) => new Promise(r => setTimeout(() => r(v), ms));

const results = await [1, 2, 3].reduce(async (p, n) => {
  const out = await p;
  out.push(await sleep(10, n * 10));
  return out;
}, Promise.resolve([]));
// [ 10, 20, 30 ]

The accumulator is a promise, and each step waits for the previous one before starting. That makes the calls run one after another, useful for rate-limited APIs. A plain for...of loop with await does the same job more readably, as shown in our async/await guide, so treat this as a pattern to recognise in existing code.

Examples 11 and 12: why the initial value matters

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

const cart = [{ price: 5 }, { price: 7 }];
cart.reduce((a, b) => a + b.price);      // '[object Object]7'
cart.reduce((a, b) => a + b.price, 0);   // 12

Without an initial value, reduce uses the first element as the accumulator and starts from the second. On an empty array there is no first element, so it throws. On an array of objects, the first object becomes the accumulator and gets glued to a number as a string, a bug that passes silently. Always pass the initial value; it also documents the type of the result.

Tip: the initial value should be the same type as the result: 0 for sums, {} for lookups, [] for lists and new Map() for maps.

["a", "b", "c"].reduceRight((acc, s) => acc + s, "");   // 'cba'
[1, , 3].reduce((acc) => acc + 1, 0);                   // 2

reduceRight works the same way but from the last element to the first. The second line shows that reduce skips holes in sparse arrays: three slots, but the callback ran only twice.

Performance: reduce vs loops

We timed each approach in Node.js 24 (best of five runs):

Task Time
Sum 1,000,000 numbers with reduce 9.90 ms
Sum 1,000,000 numbers with for...of 7.24 ms
Index 5,000 objects, spreading the accumulator 10.87 ms
Index 5,000 objects, mutating the accumulator 0.12 ms

Reduce versus a loop is a small difference for sums. The big trap is (acc, o) => ({ ...acc, [o.id]: o }). It copies the whole accumulator on every step, so the work grows with the square of the array length. Mutating an accumulator you created yourself, as in the second index example, is safe and about 90 times faster here. The spread operator guide covers this cost in more detail.

When not to use reduce

  • Simple transforms: use map or filter, which say what they do.
  • Grouping only: use Object.groupBy or Map.groupBy.
  • Flattening: use flat() or flatMap().
  • Early exit: reduce always visits every element; use some, find or a loop with break.
  • Long multi-step reducers: if a reducer needs comments to explain it, a for...of loop is usually easier to review.

Python has the same idea in functools.reduce; compare the styles in our Python map and filter guide.

Final thoughts

JavaScript reduce is a single tool for turning many values into one. Pass an initial value every time, return the accumulator from every call, mutate your own accumulator instead of spreading it, and choose a clearer built-in when one exists. Used that way, reduce produces short, fast code for totals, tallies, lookups and pipelines.

Frequently asked questions

What does reduce return in JavaScript?

It returns the final value of the accumulator after the reducer has run on every element. That value can be a number, string, array, object, Map or promise.

Why do I get Reduce of empty array with no initial value?

You called reduce on an empty array without an initial value, so there is nothing to start from. Pass an initial value as the second argument, such as 0 or an empty object.

Is reduce slower than a for loop?

Slightly. In our Node.js 24 test, summing a million numbers took 9.90 ms with reduce and 7.24 ms with a for of loop. Copying the accumulator on every step is the real slowdown to avoid.

Can reduce return an object?

Yes. Pass an empty object as the initial value, add keys inside the reducer and return the object. This is common for counting items and building lookups by ID.

What is the difference between reduce and reduceRight?

reduce processes elements from first to last, while reduceRight processes them from last to first. Otherwise they take the same arguments and work the same way.

Keep learning

Work with Stack Quora

Need help with testing, WordPress or SEO?

We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

Softmax Function Explained: Formula, Python Code and Stable Version

The softmax function explained: formula, worked example, NumPy code, the stable version that avoids NaN, temperature, cross-entropy and softmax vs…

Read article →
Software Development

CORS Explained: Preflight Requests, Headers and How to Fix CORS Errors

CORS explained: origins, simple and preflight requests, the response headers your server must send, credentials, and how to fix common…

Read article →
DevOps

Git Diff Explained: Staged Changes, Branches and Commits

Git diff explained: read the output, compare unstaged and staged changes, commits and branches, two dots vs three dots, and…

Read article →
Test Automation

Pytest Xdist: Run Tests in Parallel and Cut Test Time

Run pytest tests in parallel with pytest-xdist: install, the -n option, distribution modes, real timings and how to fix shared-state…

Read article →
Software Testing

Verification vs Validation in Software Testing: Example and Table

Verification vs validation in software testing explained with a comparison table and a tested coupon example where every spec test…

Read article →
Databases & SQL

SQL CAST Explained: Convert Data Types With Tested Examples

SQL CAST explained with tested examples: text to number, truncation, integer division, numbers stored as text, dates, bad input and…

Read article →
Databases & SQL

SQL DISTINCT: How to Remove Duplicate Rows (and Its Traps)

SQL DISTINCT explained with tested queries: one and many columns, NULLs, COUNT DISTINCT, DISTINCT vs GROUP BY, the SUM DISTINCT…

Read article →
Software Development

JavaScript Reduce Explained: 12 Practical Examples

JavaScript reduce explained step by step with 12 practical examples: sums, tallies, grouping, Maps, pipelines, sequential promises and the empty…

Read article →
Software Development

Python Random Module: randint, choice, seed and More

The Python random module explained: randint, randrange, choice, choices, sample, shuffle, seed, weights and when to use secrets instead, with…

Read article →
Software Development

Python Slicing Explained: Start, Stop and Step With Examples

Python slicing explained with start, stop and step, negative indexes, reversing, copying and slice assignment, with tested examples and a…

Read article →
Artificial Intelligence

Levenshtein Distance: Formula, Worked Table and Python Code

Levenshtein distance explained: the edit operations, the dynamic programming table for kitten and sitting, Python code with two-row memory, normalised…

Read article →
Software Development

URL Encoding Explained: Spaces, Plus Signs and UTF-8

URL encoding explained with tested Python and JavaScript code: percent encoding, reserved characters, %20 vs plus, UTF-8 bytes, encodeURI vs…

Read article →
DevOps

Gitignore: Patterns, Negation and Fixing Tracked Files

A tested gitignore guide: pattern rules, leading and trailing slashes, negation with !, the ignored parent folder trap, git check-ignore…

Read article →
Software Testing

Acceptance Criteria: Given When Then Examples and Checklist

How to write acceptance criteria testers can run: rule-based and Given When Then formats, a worked discount code example turned…

Read article →
Software Testing

State Transition Testing: Diagram, Table and Example

State transition testing explained with a login lockout example: states, events, the diagram, the state table, valid and invalid transitions,…

Read article →
Databases & SQL

Second Highest Salary in SQL: 5 Tested Ways and the Tie Trap

Find the second highest salary in SQL five ways: MAX subquery, LIMIT OFFSET, DENSE_RANK, a correlated subquery and per department,…

Read article →
Databases & SQL

SQL ROW_NUMBER: Top N per Group, Dedupe and Pagination

SQL ROW_NUMBER explained with tested queries: PARTITION BY, top N per group, deleting duplicates, pagination, the tie trap and how…

Read article →
Software Development

JavaScript Set: Union, Intersection and Removing Duplicates

JavaScript Set explained with tested examples: add, has, delete, deduplicating arrays, the new union and intersection methods, equality rules and…

Read article →
Test Automation

Python Unittest: Assert Methods, setUp and Mocks With Examples

A practical Python unittest tutorial: TestCase, assert methods, setUp and tearDown, subTest, skips, expected failures and mock, with a test…

Read article →
Artificial Intelligence

Jaccard Similarity: Formula, Python, MinHash

Jaccard similarity measures overlap between two sets as intersection over union. Work the formula, compute it in Python for words…

Read article →
DevOps

Git Hooks: Pre-commit and Commit-msg Examples

Git hooks run scripts at key moments such as commit and push. See tested pre-commit, commit-msg and prepare-commit-msg hooks, sharing…

Read article →
Test Automation

API Testing in Python: Pytest + Requests Suite

Build an API testing suite in Python with pytest and requests: fixtures, status codes, headers, JSON schema validation, CRUD flows,…

Read article →
Software Testing

Test Design Techniques: 9 Methods + Examples

Test design techniques help you write fewer tests that catch more bugs. Learn 9 black-box, white-box and experience-based methods with…

Read article →
Databases & SQL

SQL Temporary Table: Create, Use and Drop It

SQL temporary tables store interim results for one session. Learn syntax for SQL Server, PostgreSQL, MySQL, Oracle and SQLite, session…

Read article →
Databases & SQL

SQL CROSS JOIN: Every Combination + Examples

SQL CROSS JOIN returns every combination of rows from two tables. See the row math, product variants, calendar grids that…

Read article →
Artificial Intelligence

TF-IDF Explained: Formula and Worked Example

TF-IDF scores a word by how often it appears in a document and how rare it is across all documents….

Read article →
DevOps

Git Tag: Create, Push and Delete Release Tags

Git tag explained with tested commands: annotated vs lightweight tags, listing and sorting, pushing with follow-tags, deleting local and remote…

Read article →
Test Automation

Pytest Coverage: pytest-cov and Branch Gaps

Measure pytest coverage with pytest-cov: term-missing reports, branch coverage, HTML reports, pyproject settings and a fail-under gate for CI, with…

Read article →
Software Testing

Error Guessing in Testing: Checklist + Demo

Error guessing uses tester experience to predict where code breaks. Get a ready checklist of risky inputs, a step by…

Read article →
Artificial Intelligence

BM25 Explained: How Keyword Search Ranks Results, With Python Code and Hybrid Search

BM25 explained with a pure Python implementation we ran: the formula, IDF, term saturation, the k1 and b parameters, why…

Read article →
DevOps

Git Bisect Explained: Find the Commit That Broke Your Code, Manually or Automatically

Git bisect explained with a tested repository: find the one bad commit among 41 in 5 test runs, automate it…

Read article →
Test Automation

pytest Markers Explained: Custom Marks, skip, skipif, xfail and -m Filters

pytest markers explained with a tested suite: register custom marks, run only smoke tests with -m, combine filters with and,…

Read article →
Software Testing

Positive vs Negative Testing: Differences, 24 Real Test Cases and a Checklist

Positive vs negative testing explained with a real signup form: 6 positive and 18 negative test cases run in pytest,…

Read article →
Artificial Intelligence

Cosine Similarity Explained: Formula, Worked Example and Python Code

Cosine similarity explained simply: the formula, a worked example by hand, pure Python and NumPy code, cosine vs Euclidean distance…

Read article →
DevOps

Git Squash Commits: 4 Easy Ways, Tested Step by Step (rebase -i, reset, merge)

Git squash commits explained with 4 tested methods: interactive rebase, reset –soft, merge –squash and fixup with autosquash. Before-and-after logs,…

Read article →
Test Automation

pytest parametrize Explained: 7 Patterns with Tested Examples

pytest parametrize explained with 7 tested patterns: basic cases, readable ids, stacked decorators, pytest.param with xfail and skip, indirect fixtures…

Read article →