# JS: Array.prototype.reduceRight

By Xah Lee. Date: . Last updated: .
• `myArray.reduceRight (f)`
• `myArray.reduceRight (f,firstValue)`

If we have the array `[1,2,3,4]`,

`[1,2,3,4].reduceRight ( f )`

Returns

`f(f(f(4,3),2),1)`

In general `reduceRight` first computes f(x,y) where x is last item in array and y is second item from right. Then, recursively apply f, taking a new array element as second argument, until the first item in array is used, and returns the result.

If firstValue is given, is used as the first value to begin. That is, start with `f(firstValue,lastElement)`

The function f is passed 4 args:

1. the previousValue (value from the previous call to f)
2. the currentValue (value of the current element)
3. the currentIndex
4. the object being traversed.

The function f should return 1 value.

```// example of reduceRight

const aa = ["a", "b", "c", "d"];

// a function that join 2 strings
const ff = function (x, y) {
console.log ( x, y );
return x + y; }

console.log(
aa.reduceRight(ff)
); // dcba

// prints

// d c
// dc b
// dcb a
// dcba```

Example with given second argument.

```// example of reduceRight

const aa = ["a", "b", "c", "d"];

// a function that join 2 strings
const ff = function (x, y) {
console.log ( x, y );
return x + y; }

console.log(
aa.reduceRight (ff, "3")
);

// prints

// 3 d
// 3d c
// 3dc b
// 3dcb a
// 3dcba```

`reduceRight` does not directly mutate the object on which it is called but the object may be mutated by f.

The range of elements processed by reduce is set before the first call to f. Elements that are appended to the array after the call to `reduceRight` begins will not be visited by f. If existing elements of the array are changed by f, their value as passed to f will be the value at the time `reduceRight` visits them; elements that are deleted after the call to `reduceRight` begins and before being visited are not visited.

## Reduce (left)

JS: Array.prototype.reduce

## Reference

ECMAScript® 2016 Language Specification#sec-array.prototype.reduceright

#### Array Topic

Liket it? Put \$5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put \$5 at patreon and message me.