Is `Array.prototype.reduceRight` identical to `reverse` followed by `reduce`?

Viewed 402

Array.prototype.reduceRight reduces an array to a single value, working right-to-left (i.e. starting from the end of the array).

Is calling reduceRight exactly the same as calling reverse followed by reduce? If so, why does reduceRight exist?

3 Answers

Array#reduceRight is not the same as Array#reverse() -> Array#reduce(). Here is the key difference .reduce()/.reduceRight() do not modify the starting array:

const arr = ["a", "b", "c"];

const combine = arr.reduceRight((a, b) => a+b, "");

console.log(combine);
console.log(arr);

However, .reverse() does:

const arr = ["a", "b", "c"];

const combine = arr.reverse().reduce((a, b) => a+b, "");

console.log(combine);
console.log(arr);

There is also question for a performance - .reverse will incur an additional O(n) processing to reverse the array in-place, that's on top of the .reduce() that already operates at O(n). Yes, the final complexity is still O(n) (we ignore the constants) but having a single pass through the array is faster.

As already mentioned, it is not the same. Here are two more use cases, where those two versions behave differently:

  • Everything that is based on the index (third argument of the callback function called by both reduce and reduceRight) might behave differently.

  • Reverse loops are often used when the original array is being modified. Depending on the exact use case, that might work with reduceRight but break with reduce.

Related