JavaScript Iterator reduce()
Example
Add all numbers in an iterator:
function myFunc(total- num) {
return total + num;
}
const myIterator = Iterator.from("123456789");
let result = myIterator.reduce(myFunc);
Try it Yourself »
Description
The reduce()
method executes a reducer function for each element.
The reduce()
method returns a single value: the function's accumulated result.
The reduce()
method does not execute the function for empty array elements.
The reduce()
method does not change the original iterator.
Note
At the first callback, there is no return value from the previous callback.
Normally, element 0 is used as initial value, and the iteration starts from element 1.
If an initial value is supplied, this is used, and the iteration starts from element 0.
Syntax
iterator.reduce(function(total, currentValue, currentIndex, arr), initialValue)
Parameters
Parameter | Description | ||||||||
function() | Required. A function to be run for each element in the iterator. |
||||||||
Reducer function parameters:
| |||||||||
initialValue | Optional. A value to be passed to the function as the initial value. |
Return Value
The accumulated result from the last call of the callback function. |
Browser Support
iterator.reduce()
is an ES2025 feature.
ES2025 is fully supported in all modern browsers since May 2025:
Chrome 135 | Edge 135 | Firefox 129 | Safari 18.2 | Opera 120 |
Apr 2025 | Apr 2025 | Aug 2024 | Des 2024 | May 2025 |