Sitemap

JavaScript reduce() Method

2 min readFeb 14, 2022

--

Press enter or click to view image in full size

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:

Press enter or click to view image in full size

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.

Press enter or click to view image in full size

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:

Press enter or click to view image in full size

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:

Press enter or click to view image in full size

Now the accumulator’s value is = 100

We are done with 100. Let’s move on to the next(currentNumberInArray) number: 200

Like so:

Press enter or click to view image in full size

Now the accumulator’s value is 300.

Next, we will add the next number(300) to the accumulator’s value:(300).

Press enter or click to view image in full size

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.

Press enter or click to view image in full size

And we’re done!

Thank you so much for reading this article. I hope this helps

--

--