0
0
JavascriptHow-ToBeginner · 3 min read

How to Use Reduce in JavaScript: Syntax and Examples

The reduce method in JavaScript processes an array to produce a single value by applying a function to each element and accumulating the result. You use it by passing a callback function and an optional initial value to array.reduce().
📐

Syntax

The reduce method takes a callback function and an optional initial value. The callback receives four arguments: the accumulator (the running total), the current element, the current index, and the original array. The method returns the final accumulated value.

javascript
array.reduce((accumulator, currentValue, currentIndex, array) => {
  // return updated accumulator
}, initialValue);
💻

Example

This example sums all numbers in an array using reduce. It starts with an initial value of 0 and adds each number to the accumulator.

javascript
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((acc, curr) => acc + curr, 0);
console.log(sum);
Output
15
⚠️

Common Pitfalls

One common mistake is forgetting to provide the initial value, which can cause errors or unexpected results, especially with empty arrays. Another is using reduce for complex tasks without clear accumulator logic, making code hard to read.

javascript
const arr = [];
// Wrong: no initial value, causes error on empty array
// const result = arr.reduce((acc, curr) => acc + curr);

// Right: provide initial value to handle empty arrays safely
const result = arr.reduce((acc, curr) => acc + curr, 0);
console.log(result);
Output
0
📊

Quick Reference

  • accumulator: holds the accumulated result
  • currentValue: current element being processed
  • initialValue: optional start value for accumulator
  • Returns the final accumulated value after processing all elements

Key Takeaways

Use reduce to combine array elements into a single value by accumulating results.
Always provide an initial value to avoid errors with empty arrays.
The callback function receives accumulator and current element as main arguments.
Reduce can be used for sums, products, arrays, objects, or any accumulated result.
Keep reduce logic simple and clear for better readability.