Difference between reduce and reduceRight method in JavaScript

Both are Array methods

. reduce function reduce the array from left to right , where as reduceRight reduces the array from right to left and give a value after performing respective calculation like addition , multiplication etc.

What the above statement actually means, before understanding this, Let's first understand how reduce and reduceRight work.

reduce function takes two things as argument 1- callback function 2- Initial value (optional)

const arr=[1,2,3,4]
const result = arr.reduce((prev,currentItem,index,array)=>prev+currentItem,3);
console.log(result) //  13

here above code since we passed initial value =3 ,

so for the first time prev=3 and currentItem =1 and prev will become prev+currentItem =4 , and then 4+2 =>6 , 6+3=>9 , 9+4= 13

then 13 will be returned.

same way reduceRight will work but it will start operation on the arrya from right .

const arr=[1,2,3,4]
const result = arr.reduceRight((prev,currentItem,index,array)=>prev+currentItem,3);
console.log(result) //  13

but in the case of reduceRight , when execution will start prev=3 and currentItem=4 , so prev=prev+currntItem, prev=7 , => 7+3 =>10 , 10+2=> 12 , 12+1 =>13

13 will be returned

reduce and reduceRight are used to implement pipe and composition functions in JavaScript

In reduce function , If we don't pass initial value , by default prev will take arr[0] , and currentItem will start from arr[1]. Same with reduceRight but there it will be starting from lastIndex of the array

will be sharing about pipe and composition later.