JavaScript reduceRight(): Fold from Right to Left
Quick answer
reduceRight() accumulates from the highest index toward zero. Order matters for operations such as subtraction or string composition.
How it works
The callback signature and initial-value rules match reduce. With no initial value, the last present index supplies the accumulator. Missing indices are skipped. The callback still receives the actual source index. Neither method reverses the source by itself.
console.log(["a", "b", "c"].reduceRight((a, x) => a + x, ""));Expected output in Node.js:
cbaTraversal starts from c.
const a = [10, 3, 2];console.log(a.reduce((x,y)=>x-y), a.reduceRight((x,y)=>x-y));Expected output in Node.js:
5 -11Left is (10-3)-2; right is (2-3)-10.
Common mistakes
A right fold is not necessarily equivalent to a left fold. Test with a noncommutative operation and an explicit initial value.
Practice
Fold a list of letters in both directions with an empty string initial value.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
JavaScript reduceRight(): Fold from Right to Left — Knowledge Check
Apply the taught concept and predict the output.
Which present value initializes reduceRight without an initial argument?
Does reduceRight reverse the array itself?
Which operation demonstrates why folding direction can matter?
What is the exact console output in JavaScript reduceRight(): Fold from Right to Left example 1?
console.log(["a", "b", "c"].reduceRight((a, x) => a + x, ""));What is the exact console output in JavaScript reduceRight(): Fold from Right to Left example 2?
const a = [10, 3, 2];console.log(a.reduce((x,y)=>x-y), a.reduceRight((x,y)=>x-y));