JavaScript Array reduceRight() Method

JavaScript Array reduceRight() Method executes a function against an accumulator and each value of the array (from right-to-left) to reduce it to a single value.

The reduceRight() method executes a reducer function for each array element.

The reduceRight() method works from right to left.

reduceRight() does not change the original array.

The reduceRight() method returns a single value: the function’s accumulated result.

The reduceRight() method does not execute the function for empty elements.

reduceRight() is an ECMAScript5 (ES5) feature.

Syntax

array.reduceRight(callbackFunction(total/accumulator, currentValue, currentIndex, arr), initialValue)
  • callbackFunction(): Required. A function to be run for each element in the array.
  • total/accumulator: Required. The initialValue, or the previously returned value of the function. It accumulates the return values of the callback function, returned in the last calling of the function.
  • currentValue: Required. The value of the current element.
  • currentIndex: Optional. The index of the current element.
  • arr: Optional. It is the source array to which the elements belong.
  • initialValue: Optional. A value to be passed to the function as the initial value. If not provided, the last element acts as the accumulator on the first call and callbackFunction() won’t execute on it.

Calling reduceRight() on an empty array without initialValue will throw TypeError.

Return Value

Returns the value resulting after reducing the array.

Example 

const numbers = [1, 2, 3, 4, 5, 6];

function sum_reducer(accumulator, currentValue) {
  return accumulator + currentValue;
}

let sum = numbers.reduceRight(sum_reducer);
console.log(sum); // 21

// using arrow function
let summation = numbers.reduceRight(
  (accumulator, currentValue) => accumulator + currentValue
);
console.log(summation); // 21