JavaScript Reference ยท Array
Array.prototype.reduceRight()
Reference for JavaScript Array.prototype.reduceRight(): fold an array from the last element to the first, when order matters, and how it differs from reduce().
The reduceRight() method works exactly like reduce(), except it visits the elements from the last index down to the first. It combines them into a single value using an accumulator.
The direction only matters when the operation is not commutative: building strings, composing functions, or folding nested structures where the right end should be processed first.
["a", "b", "c"].reduceRight((acc, ch) => acc + ch, ""); // "cba"
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
array.reduceRight(callbackFn) array.reduceRight(callbackFn, initialValue)
| Name | Description |
|---|---|
callbackFn |
Called as callbackFn(accumulator, currentValue, currentIndex, array). Its return value becomes the next accumulator. |
initialValue |
Optional. The starting accumulator. If omitted, the last element is used and iteration starts at the second-to-last. |
Return value: the final accumulator value.
Exceptions: a TypeError if callbackFn is not a function, or if the array is empty and no initialValue was given.
Usage notes
- Same rules as
reduce(), only the direction changes. The indexes passed to the callback go down, fromlength - 1to0. - Subtraction and string building show the difference most clearly.
[1, 2, 3, 4].reduceRight((a, n) => a - n)is4 - 3 - 2 - 1, which is-2. - Function composition is the classic use:
compose(f, g)(x)computesf(g(x))by applyinggfirst. - It does not mutate the array. The callback can still mutate the accumulator.
- Always supply an initial value to avoid the
TypeErroron empty arrays and to fix the result type. - Holes are skipped, as in
reduce(). - Alternative:
array.toReversed().reduce(...)gives the same visiting order but allocates a copy;reduceRight()does not.
Browser support
Array.prototype.reduceRight() is part of ES5 and works in every browser in use today.