The Reducer Function Signature
What you'll learn: The four parameters that a reducer function receives from Array.prototype.reduce.
When you pass a callback function to reduce(), JavaScript automatically supplies it with up to four parameters in a specific order. Understanding these parameters is essential to using reduce effectively.
The Four Parameters
Your reducer function can accept these arguments (in order):
- accumulator – The value being built up across iterations (sometimes called "acc" or "result")
- currentValue – The current element being processed (sometimes called "current" or "item")
- currentIndex – The position of the current element in the array
- array – The original array being reduced
function reducer(accumulator, currentValue, currentIndex, array) {
// Your logic here
return accumulator; // Must return updated accumulator
}
const numbers = [1, 2, 3];
numbers.reduce(reducer, 0);
Think of It Like This
Imagine an assembly line where you're building something:
- accumulator: The partially completed product moving down the line
- currentValue: The next part to add
- currentIndex: Which station you're at
- array: The blueprint showing all parts
You Don't Need All Four
Most reduce operations only use the first two parameters:
const sum = [1, 2, 3, 4].reduce((acc, num) => acc + num, 0);
// Only using accumulator and currentValue
The index and array parameters are available when you need them, but they're optional.
Key Takeaway: Every reducer function receives four parameters—accumulator, currentValue, currentIndex, and array—though you typically only use the first two for most operations.