Example 1 — Sum from the Right
Fold numbers with reduceRight and an initialValue of 0.
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduceRight((acc, num) => acc + num, 0);
console.log(sum);
// 15 How It Works
- Start at zero.
initialValue0is the first accumulator. - Walk right to left. Steps visit
5, then4, then3, then2, then1. - Add each value. Because addition commutes, the total is still
15— same asreduce. - Source untouched.
numbersstays[1, 2, 3, 4, 5].

