The JavaScript Array reduceRight() method combines array elements into one result while processing them from right to left. Like reduce(), it uses a callback and an accumulator, but the direction changes the order in which the callback sees the elements. This tutorial adds examples showing when that reverse order matters, how to compose functions, and how sparse arrays are handled.
Syntax and Formal Specification
The method signature is reduceRight(callbackFn, initialValue).
const numbers = [1, 2, 3, 4, 5]; const sum = numbers.reduceRight((acc, n) => acc + n, 0); console.log(sum); // 15 (same as reduce() for associative +)
Parameters
-
callbackFn— A function invoked for each element. It receives four arguments:-
accumulator— The value returned from the previous callback invocation (or the initial value on the first call). -
element— The current element being processed. -
index— The integer index of the current element. -
array— The array on whichreduceRight()was called.
-
-
initialValue(optional) — The initial value of the accumulator. If provided, iteration starts at indexlength - 1. If omitted, the last element is used as the initial accumulator, and iteration starts at indexlength - 2.
Return Value
The final accumulator value after all elements have been processed. The return type is whatever the reducer returns—anything from a primitive to an object to a function.
The Critical Difference: With vs Without initialValue
Like reduce(), the optional initialValue changes behavior fundamentally, but in a directionally-mirrored way.
With initialValue:
-
Iteration starts at the last index (
length - 1). -
The accumulator starts as
initialValue. -
The reducer runs
lengthtimes. -
Empty arrays return
initialValue(no error).
Without initialValue:
-
Iteration starts at the second-to-last index (
length - 2). -
The accumulator starts as the last element (
arr[length - 1]). -
The reducer runs
length - 1times. -
Empty arrays throw a
TypeError(“Reduce of empty array with no initial value”). -
Single-element arrays return the element unchanged without invoking the callback.
// With initial value: safe for empty arrays console.log([].reduceRight((a, b) => a + b, 0)); // 0 (no error) // Without initial value: empty array throws try { [].reduceRight((a, b) => a + b); } catch (e) { console.log(e.constructor.name); // "TypeError" } // Without initial value: single element returned as-is console.log([5].reduceRight((a, b) => a + b)); // 5 // With initial value: callback invoked even for single element console.log([5].reduceRight((a, b) => a + b, 10)); // 15
Always provide initialValue unless you have a specific reason not to. This avoids the empty-array error, makes the code self-documenting, and handles all input sizes uniformly.
Accumulator Mutation: A Cautionary Note
In reducers that accumulate into an object or array, mutating the accumulator in place is common for performance:
const words = ["apple", "apricot", "banana", "blueberry", "cherry"]; // Builds groups in reverse-visit order const grouped = words.reduceRight((acc, word) => { const letter = word[0]; if (!acc[letter]) acc[letter] = []; acc[letter].push(word); // mutate accumulator return acc; }, {}); console.log(grouped); // { c: ["cherry"], b: ["blueberry","banana"], a: ["apricot","apple"] } // Each group's items are in reverse of original order
The immutable alternative returns a fresh accumulator each step, which is safer but O(n²) for large arrays:
const groupedImmutable = words.reduceRight((acc, word) => { const letter = word[0]; return { ...acc, [letter]: [...(acc[letter] || []), word] }; }, {});
Use mutation for performance, immutable patterns for functional purity.
reduceRight() vs Manual Reverse Loop
reduceRight() is typically slightly slower than an explicit for loop with descending index because of the callback invocation overhead. For hot loops over large arrays, a manual loop can be 1.5×–2× faster:
const big = new Array(1_000_000).fill(1); const t1 = performance.now(); const sumReduce = big.reduceRight((a, b) => a + b, 0); console.log(performance.now() - t1); const t2 = performance.now(); let sumLoop = 0; for (let i = big.length - 1; i >= 0; i--) sumLoop += big[i]; console.log(performance.now() - t2); console.log(sumReduce === sumLoop); // true
For most application code, the readability of reduceRight() outweighs the micro-optimization.
reduceRight() vs reverse().reduce()
A common alternative to reduceRight() is to reverse the array and use reduce(). This is almost always slower because reverse() mutates the array (requiring a defensive copy) and reduce() still runs the same number of callbacks:
const arr = [1, 2, 3, 4, 5]; // Slower: copies array via spread, reverses, then reduces const viaReverse = [...arr].reverse().reduce((a, b) => a - b); // Faster: single pass, no copy const viaReduceRight = arr.reduceRight((a, b) => b - a); console.log(viaReverse, viaReduceRight); // -13 -13
Early Termination: reduceRight() Cannot Short-Circuit
Like reduce(), reduceRight() cannot terminate early. The reducer runs for every non-hole element, even after the accumulator has reached its final value. If early exit is needed, use a different method or wrap the reducer with a flag:
// Cannot short-circuit: reducer runs for all elements const lastMatch = items.reduceRight((acc, item) => { if (acc !== null) return acc; // "already found, skip" return item.id === targetId ? item : null; }, null); // Prefer findLast() when short-circuiting from the end const lastMatch2 = items.findLast(item => item.id === targetId);
See how direction changes an order-sensitive result
For operations where order matters, reduceRight() can produce a different result from reduce(). Subtraction is not associative, so grouping the same values in the opposite direction changes the answer.
const values = [10, 3, 2];
const leftToRight = values.reduce((acc, value) => acc - value, 0);
const rightToLeft = values.reduceRight(
(acc, value) => value - acc,
0
);
console.log(leftToRight); // 5: ((0 - 10) - 3) - 2
console.log(rightToLeft); // 9: 10 - (3 - (2 - 0))
For addition, reversing the order usually produces the same total because addition is associative and commutative for ordinary values. For strings, subtraction, division, or other order-sensitive operations, check the callback’s argument order carefully.
Compose functions from right to left
A classic use for reduceRight() is combining small functions into a pipeline. In the following example, functions are applied from right to left: the value is multiplied by 3, then increased by 2.
const operations = [
value => value + 2,
value => value * 3
];
const composed = operations.reduceRight(
(next, operation) => value => operation(next(value)),
value => value
);
console.log(composed(4)); // 14: (4 * 3) + 2
The initial function returns its input unchanged. Each reducer call wraps the current composition with another function. This pattern is useful in functional programming and middleware pipelines, though a named helper can make it clearer if the composition logic is unfamiliar to the team.
Build a reversed string from an array
Because the callback starts at the final element, reduceRight() can build a reversed sequence without mutating the source array. Array.from() first creates an array of Unicode code points, which handles characters represented by a surrogate pair better than indexing a string directly.
const letters = Array.from("hello");
const reversed = letters.reduceRight(
(result, letter) => result + letter,
""
);
console.log(reversed); // "olleh"
console.log(letters.join("")); // "hello"
This reverses code points, not user-perceived grapheme clusters. A visible symbol made from multiple code points, such as a letter plus a combining mark, may still need a grapheme-aware approach for perfect text reversal.
How reduceRight() handles sparse arrays
reduceRight() skips empty slots in a sparse array, just as reduce() does. It visits present elements from the highest index down and does not call the reducer for a hole. If no initialValue is given, it searches backward for the first present element to use as the starting accumulator.
const sparse = [1, , 3];
const visited = sparse.reduceRight((result, value) => {
result.push(value);
return result;
}, []);
console.log(visited); // [3, 1]
The result is an array built in callback visit order. An explicit undefined value is present and is passed to the callback; a hole is absent and is skipped. If all positions are holes and there is no initial value, the method throws a TypeError.
Use the callback index to inspect positions
The callback’s index decreases as reduceRight() moves toward the start of the array. The third callback argument is still the original array. These values can help when the transformation depends on an element’s position.
const steps = ["start", "middle", "end"];
const trace = steps.reduceRight((result, step, index, array) => {
result.push(`${index}: ${step} of ${array.length}`);
return result;
}, []);
console.log(trace);
// ["2: end of 3", "1: middle of 3", "0: start of 3"]
The accumulated array in this example records the reverse visitation order. If the final result needs to be in the original order instead, reverse that new result or build it by prepending values—choose whichever makes the data flow clearest.