JavaScript Iterator reduce()
Example
Add all numbers in an iterator:
return total + num;
}
// Create an Iterator
const myIterator = Iterator.from("123456789");
// Reduce to sum
let result = myIterator.reduce(myFunc);
Description
The reduce()
method executes a reducer function for each element.
The reduce()
method returns the function's accumulated result.
The reduce()
method does not execute the function for empty 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
Parameters
A function to be run for each element in the iterator.
The initialValue, or the previously returned value of the function.
The value of the current element.
The index of the current element.
The iterator of the current element.
A value to be passed to the function as the initial value.
Return Value
Browser Support
iterator.reduce()
is a JavaScript 2025 feature.
ES 2025 is fully supported in all modern browsers since May 2025:
Chrome 136 |
Edge 136 |
Firefox 129 |
Safari 18.2 |
Opera 120 |
Apr 2025 | Apr 2025 | Aug 2024 | Des 2024 | May 2025 |