Emmanuel Akinfulubi

JavaScriptArray

reduce vs reduceRight in JavaScript

Intermediate · 3 min read

reduce walks through an array from the first item to the last. reduceRight does exactly the same job, but starts at the last item and walks back to the first. For most jobs, like a sum, the direction makes no difference. For a few, it changes the answer completely.

In this tutorial you will see reduceRight visit items in reverse, find operations where direction matters, and use it to build compose, a way to chain functions together that libraries use a lot. You should know arrow functions and the basics of reduce.

Folding, left and right

Using reduce to squash a list into one value is often called folding it. reduce folds from the left. reduceRight folds from the right. With no starting value, each one starts with the item at its own end.

JavaScript

const letters = ['a', 'b', 'c'];
console.log(letters.reduce((a, b) => a + b));      // abc
console.log(letters.reduceRight((a, b) => a + b)); // cba

Joining strings depends on the order, so the two directions give two different words.

Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.

35 reduceRight, and why direction matters

fair

Fold an array from the right. Find an operation where the direction changes the answer, and use reduceRight to compose functions.

Stuck? Three hints, smallest first
  1. 1. reduceRight starts at the last element and works towards the first.
  2. 2. Addition does not care about direction; subtraction and string concatenation do.
  3. 3. Function composition is reduceRight by definition: f(g(x)) applies g first.

Step 1: watch the order

To see which item is visited when, record the index each time the callback runs. The callback's third argument is the index.

Step 1

const letters = ['a', 'b', 'c'];
const visitedRight = [];
letters.reduceRight((acc, v, i) => { visitedRight.push(i); return acc; }, null);
console.log(visitedRight); // [ 2, 1, 0 ]

The starting value is null here, so every item is visited, from index 2 down to 0. The callback ignores the items and just writes down where it is.

Step 2: when direction doesn't matter

Step 2

const nums = [10, 3, 2];
console.log(nums.reduce((a, b) => a + b, 0));      // 15
console.log(nums.reduceRight((a, b) => a + b, 0)); // 15

Adding in any order gives the same total, so for a sum it makes no difference. The same goes for a count or a maximum. In those cases, use plain reduce: people read it more easily.

Step 3: when it does

Subtraction cares about order.

Step 3

const nums = [10, 3, 2];
console.log(nums.reduce((a, b) => a - b));      // 5
console.log(nums.reduceRight((a, b) => a - b)); // -11

reduce works out 10 - 3 - 2, which is 5. reduceRight starts with 2 and works out 2 - 3 - 10, which is -11. Operations like subtraction and joining strings, where grouping and order change the answer, are where reduceRight earns its place.

Step 4: functions in a list

The best use of reduceRight is chaining functions. Here are two small ones:

Step 4

const double = (n) => n * 2;
const increment = (n) => n + 1;
console.log(double(increment(5))); // 12
console.log(increment(double(5))); // 11

double(increment(5)) runs the inner function first: 5 + 1 is 6, then 6 * 2 is 12. Swap them and you get 11. Order matters again.

Step 5: compose and pipe

compose(double, increment) builds a new function that means double(increment(x)). The functions are written left to right, but the rightmost one runs first. That is reduceRight: start from the value, and feed it through the functions from the right.

Step 5

const double = (n) => n * 2;
const increment = (n) => n + 1;
const compose = (...fns) => (x) => fns.reduceRight((v, f) => f(v), x);
const pipe = (...fns) => (x) => fns.reduce((v, f) => f(v), x);
console.log(compose(double, increment)(5)); // 12
console.log(pipe(double, increment)(5));    // 11

Read compose slowly. ...fns collects the functions into an array. The result is a function of x. Inside, the accumulator v starts as x, and each step replaces it with f(v). Going from the right, increment runs first, then double.

pipe is the same with reduce, so the functions run in reading order. Many people find pipe easier to follow, since it reads like a list of steps. When a library offers compose, check which direction it goes.

Step 6: an empty array

reduceRight has the same rule as reduce: with no starting value, an empty array throws.

Step 6

try {
  [].reduceRight((a, b) => a + b);
} catch (e) {
  console.log(e.constructor.name); // TypeError
}

Give it a starting value whenever the array might be empty.

The full solution

The panel folds the letters both ways, records the visiting order, subtracts both ways, and builds compose and pipe. Press Run and compare 12 with 11.

The answer

const letters = ['a', 'b', 'c'];
const nums = [10, 3, 2];

const visitedRight = [];
letters.reduceRight((acc, v, i) => { visitedRight.push(i); return acc; }, null);

const double = (n) => n * 2;
const increment = (n) => n + 1;

// compose applies right to left; pipe applies left to right.
const compose = (...fns) => (x) => fns.reduceRight((v, f) => f(v), x);
const pipe = (...fns) => (x) => fns.reduce((v, f) => f(v), x);

const emptyRight = (() => {
  try { return [].reduceRight((a, b) => a + b); } catch (e) { return e.constructor.name; }
})();

console.log('reduce      :', letters.reduce((a, b) => a + b));
console.log('reduceRight :', letters.reduceRight((a, b) => a + b));
console.log('indexes visited by reduceRight:', visitedRight);
console.log('--- subtraction is not symmetric ---');
console.log('reduce      : 10 - 3 - 2 =', nums.reduce((a, b) => a - b));
console.log('reduceRight :  2 - 3 - 10 =', nums.reduceRight((a, b) => a - b));
console.log('compose(double, increment)(5):', compose(double, increment)(5), '<- increment first');
console.log('pipe(double, increment)(5)   :', pipe(double, increment)(5), '<- double first');

Output


      
9 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 9 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

9 checks

test('reduce folds left to right', letters.reduce((a, b) => a + b), 'abc');
test('reduceRight folds right to left', letters.reduceRight((a, b) => a + b), 'cba');
test('it visits the indexes in reverse', visitedRight, [2, 1, 0]);
test('a sum is the same either way', nums.reduce((a, b) => a + b, 0), nums.reduceRight((a, b) => a + b, 0));
test('a subtraction is not', nums.reduce((a, b) => a - b), 5);
test('the right fold gives a different number', nums.reduceRight((a, b) => a - b), -11);
test('compose applies the rightmost function first', compose(double, increment)(5), 12);
test('pipe applies the leftmost first', pipe(double, increment)(5), 11);
test('reduceRight on an empty array with no seed throws too', emptyRight, 'TypeError');

reduceRight earns its keep in exactly two situations: an operation that is not associative, and function composition. For a sum, a count or a maximum it is a coin flip and reduce reads better.

The compose/pipe pair is the clearest illustration. compose(double, increment) means double(increment(x)), which is reduceRight; pipe means the same list applied in reading order, which is reduce. Both are four tokens of real work, and both are worth writing once so you never have to guess which direction a library's compose goes.

Common mistakes

  • Using reduceRight for a sum. It works, but readers wonder why. Use reduce when direction doesn't matter.
  • Mixing up compose and pipe. compose(f, g) runs g first; pipe(f, g) runs f first.
  • Leaving out the starting value. On an empty array, both reduce and reduceRight throw a TypeError.

Try it yourself

  1. Use reduceRight to reverse the string 'lagos' after splitting it into letters.
  2. Build pipe(trim, toLowerCase) for strings, using (s) => s.trim() and (s) => s.toLowerCase(), and run it on ' HeLLo '.
  3. Work out by hand what [2, 3, 2].reduceRight((a, b) => a ** b) gives, then check it.

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.