ReduceRight: Iterating from Right to Left
You'll learn: How reduceRight() processes arrays backwards and when direction actually matters.
What is ReduceRight?
reduceRight() is reduce()'s mirror twin—it does everything reduce() does, but walks through your array from the last element to the first. Same signature, same accumulator pattern, just backwards.
const numbers = [1, 2, 3, 4];
// Regular reduce: left to right
const leftResult = numbers.reduce((acc, curr) => acc - curr);
// 1 - 2 - 3 - 4 = -8
// ReduceRight: right to left
const rightResult = numbers.reduceRight((acc, curr) => acc - curr);
// 4 - 3 - 2 - 1 = -2
When Direction Actually Matters
For commutative operations (addition, multiplication), direction doesn't matter—you'll get the same result either way. But for order-sensitive operations, reduceRight() shines:
const words = ['Hello', 'beautiful', 'world'];
// Building a sentence from left
words.reduce((sentence, word) => sentence + ' ' + word);
// "Hello beautiful world"
// Building from right
words.reduceRight((sentence, word) => word + ' ' + sentence);
// "Hello beautiful world" (same, but composed backwards)
Practical Use: Reversing Nested Structures
const functions = [
(x) => x + 1,
(x) => x * 2,
(x) => x - 3
];
// Apply functions right-to-left (composition)
const result = functions.reduceRight((value, fn) => fn(value), 10);
// (10 - 3) * 2 + 1 = 15
Key Takeaway: reduceRight() processes arrays from right to left—use it when operation order matters, like function composition or right-to-left calculations.