In JavaScript, reduce()
is a higher-order function used for accumulating or “folding” values in an array, similar to the fold operation in functional programming. It applies a callback function to each element, accumulating a result. The syntax is:
javascript
array.reduce((accumulator, currentValue) => {
// Logic to combine accumulator and currentValue
return newAccumulator;
}, initialValue);
accumulator
: The accumulated value across iterations.currentValue
: The current element being processed.initialValue
: The initial value for the accumulator.
Example: Summing numbers in an array:
javascript
const sum = [1, 2, 3].reduce((acc, val) => acc + val, 0); // 6
This is an essential tool for functional programming in JavaScript.