Tanveer Sayem / 2022-11-18
2 min read
To understand reduce we would have to understand what is happening in the above code.let numbers = [1,2,3,4,5]; let sum = 0; for(let i = 0; i < numbers.length; i++) { sum += numbers[i]; } console.log(sum); // 15
numbers
sum
where we would want to store the total of all the values from the numbers
arraysum
variable abovesum
variable as it stores the final totalsum
variable here as the accumulator, meaning it is eventually responsible to store the result of the for loop, and i
in the
for loop as the current value because i
represent the current value like 1,2,3... as it iterates through the array.
So, what is happening in the above code? If you look closely you will see that all we are doing here is calling the sum variable in this case calling it accumulator, inside our callback function in reduce rather than outside,Let's rewrite the above code but with reduce. let numbers = [1,2,3,4,5]; const total = numbers.reduce((accumulator, currentValue) => { return accumulator + currentValue; }, 0) console.log(total); // 15
currentvalue
is equivalent to i
in our previous example, so it iterates through the array numbers
and adding it to the value. But what value? We did initiate the sum
variable in the previous example with 0. We are doing the same thing here as well, the 0 after the
curly braces is the initial value of the accumulator
. So, lets write the code more descriptivelylet numbers = [1,2,3,4,5]; const total = numbers.reduce((accumulator (or sum), currentValue (or i )) => { return accumulator + currentValue; }, initial value of accumulator) console.log(total); // 15
let numbers = [1,2,3,4,5]; const total = numbers.reduce((acc, curr) => (acc + curr)); console.log(total) // 15
Get emails from me about web development, tech, and early access to new articles.