JavaScript Array reduceRight() method
executes a reducer function on each element in the array (from right-to-left) to reduce it to a single value

reduceRight() method executes a reducer function on each element in the array (from right-to-left) to reduce it to a single value.

reduceRight() method returns a single value (can be a number, string, object, array).

reduceRight() method works from right to left.

syntax

reduceRight(callbackFn, initialValue) A function to execute for each element in the array ↴

function is called with the following arguments ↴

reduceRight(function(accumulator, currentValue, currentIndex, array, initialValue))

accumulator contains the value calculated from the previous iteration.

On the first iteration, if an initialValue is provided, the accumulator will be set to the value of initialValue.

The accumulator parameter is the single value that will be returned by the reduceRight() method.

currentValue current value of the element being passed from the array.

currentIndex index of the element being passed from the array.

currentIndex index of the element being passed from the array.

At the first callback, there is no return value from the previous callback.

Normally, the last array element is used as initial value, and the iteration starts from the element before.

If an initial value is supplied, this is used, and the iteration starts from last element.

array original array on which the reduceRight() method was called.

 initialValue  (optional). If initialValue is not specified, accumulator is initialized to the last value in the array.

reduceRight() method returns the value that results from the reduction.

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

reduceRight() method does not change the original array.

If no elements and initialValue is not provided TypeError is thrown.

syntax 1 description
execute a reducer function on array elements and return a single value
myArray.reduceRight(callbackFn, initialValue)
syntax 2 description
execute a reducer function on the books array and return a single value
myArray.reduceRight(callbackFn, initialValue)

// most popular books by Roald Dahl

const books = [

{ title: "Charlie and the Chocolate Factory", published: "1964", pages: 192, price: 5.59 },

{ title: "Fantastic Mr Fox", published: "1970", pages: 112, price: 5.79 },

{ title: "The BFG", published: "1982", pages: 194, price: 5.29 },

{ title: "Matilda", published: "1988", pages: 256, price: 5.49 },

{ title: "James and the Giant Peach", published: "1961", pages: 160, price: 5.89 },

{ title: "The Witches", published: "1983", pages: 224, price: 5.39 },

]