JavaScript reduce() Function
Subject: JavaScript
The reduce() function in JavaScript is a powerful array method used to reduce all elements of an array into a single output value. It does this by applying a callback function that processes each element and updates an accumulator.
What is reduce() in JavaScript?
The reduce() method loops through an array and maintains an accumulator that stores the result of each callback iteration. It’s perfect for operations like summing numbers, averaging values, flattening arrays, or building objects.
Parameters:
- accumulator: Carries the accumulated result.
- currentValue: Current array element being processed.
- index (optional): Index of the current item.
- array (optional): The array being reduced.
- initialValue: Starting value of the accumulator.
Example 1: Sum of Array Elements
Example 2: Find Maximum Value
Example 3: Convert Array to Object
Example 4: Flatten an Array of Arrays
Example 5: Calculate Average
When to Use reduce()
- When calculating totals, averages, or other cumulative results
- When converting arrays to objects or strings
- When chaining with other array methods (
filter(),map())
Common Mistakes
- ❌ Not passing an
initialValuecan lead to bugs with empty arrays or when dealing with non-numeric values. - ✅ Always make sure your callback returns the accumulator.
Key Takeaways
reduce()transforms arrays into a single value.- Requires a callback and optionally an initial value.
- Excellent for summation, aggregation, and object transformation.
- More powerful than
map()orfilter()when your end result is not another array.