Array.prototype.reduceRight()
Identical to reduce in every respect except direction: it starts at the last element and works towards the first. For a sum that changes nothing, and for anything order-dependent it changes everything.
Demo
String concatenation makes the direction visible: ['a','b','c'] folds to 'cba', where plain reduce gives 'abc'. That is the whole difference. The single-element case returns that element without ever calling the callback, because with no initial value the last element IS the seed and there is nothing left to fold into it. The empty case throws the same TypeError reduce does, for the same reason — no seed, and no element to borrow one from.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| callback | Function | yes | Called as callback(accumulator, element, index, array). The index still reports the real position, so it counts DOWN. |
| initialValue | any | no (last element) | Starting accumulator. Omitted, the LAST element is used and iteration starts at the second-to-last — so an empty array throws. |
Return value
any — Whatever the callback returned on the final iteration — which here is the one at index 0. With an initialValue and an empty array, that value comes straight back.
Common patterns
const compose = (...fns) => x => fns.reduceRight((acc, f) => f(acc), x);
const flat = nested.reduceRight((acc, x) => acc.concat(x), []);
const wrapped = layers.reduceRight((inner, L) => L(inner), core);
Examples
Pitfalls
[1, 2, 3].reduceRight((a, b) => a + b, 0)
[1, 2, 3].reduce((a, b) => a + b, 0)
[1, 2, 3].reduceRight((a, b) => a - b)
[1, 2, 3].reduceRight((acc, el) => acc - el)
[].reduceRight((a, b) => a + b)
[].reduceRight((a, b) => a + b, 0)
items.reverse().reduce(f)
items.reduceRight(f)
When to use
- Function composition, where the rightmost function should apply first
- Folding a non-commutative operation from the end — concatenation, subtraction, division
- Building nested structures from the innermost layer outwards
- Anywhere you would otherwise reverse a copy just to reduce it
- The operation is commutative → reduce, which reads more plainly
- You want the array reversed as a value → toReversed
- One value out per value in → map
- You only need the last element → at(-1)
Notes
FAQ
Only when the callback is not commutative — when f(a, b) and f(b, a) disagree. Addition, multiplication and Math.max give identical results either way. Concatenation, subtraction, division and anything that builds an ordered structure do not.
['a','b','c'].reduce((a, b) => a + b); // 'abc' ['a','b','c'].reduceRight((a, b) => a + b); // 'cba'