The reduce() method executes a reducer function on each element of the array and returns a single output value.
Example
const message = ["JavaScript ", "is ", "fun."];
// function to join each string elements
function joinStrings(accumulator, currentValue) {
return accumulator + currentValue;
}
// reduce join each element of the string
let joinedString = message.reduce(joinStrings);
console.log(joinedString);
// Output: JavaScript is fun.
reduce() Syntax
The syntax of the reduce() method is:
arr.reduce(callback(accumulator, currentValue), initialValue)
Here, arr is an array.
reduce() Parameters
The reduce() method takes in:
- callback - The callback function to execute on each array element (except the first element if no initialValue is provided). It takes in
- accumulator - It accumulates the callback's return values.
- currentValue - The current element being passed from the array.