How To Use Reduce( ) in Javascript

[10,1000].reduce( (finalValue, whatToAddToFinalValue) => finalValue + whatToAddToFinalValue );

The array has 2 items [10, 1000], which means we run 2 iterations.

On each iteration, reduces() takes 1 item ONLY!

For the FIRST iteration, since we did not declare the finalValue starting value, so it will always be 0 :

We have whatToAddToFinalValue variable, which will get its value from the array – but one item at a time.

// FIRST ITERATION

finalValue = 0

whatToAddToFinalValue = 10 // the first item in the array

====== at the end of iteration, finalValue = 10

At the subsequent iteration, we will work with a new set of data :

// SECOND ITERATION

finalValue = 10

whatToAddToFinalValue = 1000 // the second item in the array

====== at the end of the second iteration, finalValue = 1010

reduce() function operation stops right here, because no more item left in the array to deal with.

You can use reduce() for a more complicated calculation. This article is meant for a beginner who is still trying to make sense of the concept of iteration.

Ready to read more about reduce()? Visit JS docs here.

Leave a comment

Your email address will not be published. Required fields are marked *