What's the Difference Between JavaScript "Array.reduce()" and "Array.reduceRight()" Methods?

JavaScript Array.reduce() vs. Array.reduceRight()

In JavaScript, the Array.prototype.reduce() and Array.prototype.reduceRight() methods only differ in terms of how they traverse elements of an array:

  • Array.prototype.reduce() starts from left-to-right;
  • Array.prototype.reduceRight() starts from right-to-left.

Other than that, there are no differences between the two; they both apply the given function against an accumulator and each value of the array, to reduce it to a single value.

Consider the following example, which illustrates the difference between the two:

const arr = ['a', 'b', 'c', 'd'];

const ltr = arr.reduce((previous, current) => previous + current);
const rtl = arr.reduceRight((previous, current) => previous + current);

console.log(ltr); // 'abcd'
console.log(rtl); // 'dcba'

Hope you found this post useful. It was published . Please show your love and support by sharing this post.