JavaScript reduce() Method
Javascript array reduce() method can be a bit confusing when you are trying to understand it. This is how I learned it. It helped. I’m sharing it and I hope it helps you too.
Let’s begin:
Let’s declare a variable and give it a named of cost:
We are going to add these numbers together and return it at the end.
Let’s declare another variable of named total. We will store the sum of cost in total.
In the above screenshot, we declared a variable of named total and set it to cost.reduce(). reduce() will take an accumulator and a current value, add them and return the total.
Let’s give the accumulator an initial value of 0, like this:
Inside the cost array, the current number is 100. Let’s add the value of the accumulator(0) and the current number(100).
Get Daniel Amoateng’s stories in your inbox
Join Medium for free to get updates from this writer.
Like this:
Now the accumulator’s value is = 100
We are done with 100. Let’s move on to the next(currentNumberInArray) number: 200
Like so:
Now the accumulator’s value is 300.
Next, we will add the next number(300) to the accumulator’s value:(300).
Now the accumulator’s value is 600.
We are done adding all the numbers.
We can return the total of the elements inside the array.
And we’re done!
Thank you so much for reading this article. I hope this helps





