JavaScript reduce() Method |
Example
Calculate the sum of all array elements:
var numbers = [65, 44, 12, 4];
function getSum(total, num) {
return total + num;
}
function myFunction(item) {
document.getElementById("demo").innerHTML = numbers.reduce(getSum);
}
Output:
125
Definition and Usage
The reduce() method executes a provided function for each value of the array (from left-to-right).
The reduce() method can be used as a higher-order function for function composition.
Note: The reduce() method does not execute the callback function for empty arrays.
Browser Support
The numbers in the table specify the first browser version that fully supports the method.
| Method | Chrome | Edge | Firefox | Safari | Opera |
|---|---|---|---|---|---|
| reduce() | Yes | 9.0 | 3.0 | 4 | 10.5 |
Syntax
array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
Parameters
| Parameter | Description | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
| function(total, currentValue, index, arr) |
Required. A function to execute on each element. Function parameters:
|
||||||||||
| initialValue | Optional. A value to be passed to the function. |
Technical Details
| Return Value: | The calculated result. |
|---|---|
| JavaScript Version: | ECMAScript 3 |
More Examples
Example
Calculate the sum of array elements after rounding:
Sum of array elements:
var numbers = [15.5, 2.3, 1.1, 4.7]; function getSum(total, num) { return total + Math.round(num); } function myFunction(item) { document.getElementById("demo").innerHTML = numbers.reduce(getSum, 0); }
YouTip