Array.prototype.reduceRight folds an array down to a single value, exactly like reduce — but it walks the elements from right to left instead of left to right. That direction matters whenever the operation isn't symmetric: right-associative composition, building a string back-to-front, or unwinding a list from the end.
Implement arrayReduceRight(arr, callback, initialValue). Starting from the last element, call callback(accumulator, currentValue, index, array) for each element moving leftward, returning the final accumulator. The initialValue is optional, and whether you pass one changes where the fold begins.
function arrayReduceRight(arr, callback, initialValue) {
// callback: (accumulator, currentValue, index, array) => nextAccumulator
// returns the final accumulator after folding right-to-left.
}
// No initial value: accumulator starts as the LAST element ('c').
arrayReduceRight(['a', 'b', 'c'], (acc, x) => acc + x); // 'cba'
// Right-to-left changes the result of a non-symmetric op:
arrayReduceRight([1, 2, 3], (a, b) => a - b); // 0 → ((3 - 2) - 1)
// vs. reduce (left-to-right) would give ((1 - 2) - 3) = -4
currentValue is the last element; index counts down from length - 1 to 0.initialValue — the accumulator starts as initialValue, and the callback runs for every element (including the last).initialValue — the accumulator starts as the last element, and the callback runs from the second-to-last element down.initialValue — throw a TypeError. This is the one input that throws.reduceRight reads the array; it never changes it.