DEV Community

loading...
Cover image for What is .reduce(), and how does it work

What is .reduce(), and how does it work

Arsenii Gorushkin
Backend developer who wants to be Fullstack and DevOps Engineer
・2 min read

Have you ever wandered what is .reduce() function in Javascript? Then this tutorial is for you! Today we will look at how .reduce() works, and what does it do.

About .reduce()

In Javascript, reduce() method is used on arrays, it cycles through every element of an array, and for each it executes a function that you have provided in the method.

How to use

.reduce() has 2 parameters, which are:

  • 1. Callback Function
  • 2. Initial Accumulator Value
array.reduce(callbackFunction, initialValue)
Enter fullscreen mode Exit fullscreen mode

Callback method has 4 parameters, which are:

  • 1. Accumulator
  • 2. Current Element
  • 3. Index of Current Element
  • 4. Array Method is Used on
array.reduce(() => {accunulator, currentElement, index, array} => {})
Enter fullscreen mode Exit fullscreen mode

In todays example, we will not be using last 2 parameters, we will keep it to just Accumulator (we'll call it a) and Current Element (we'll call it b).

Throughout each iteration, returned value from callback function is added to the accumulator, which is stored until the end of the iteration and then returned as a single value.

EXAMPLE

const array = [1, 2, 3, 4];

console.log(array.reduce((a, b) => a + b))
// 1 + 2 + 3 + 4
//Logs out "10"

console.log(array.reduce((a, b) => a + b, 10))
// 10 + 1 + 2 + 3 + 4
//Logs out "20"
Enter fullscreen mode Exit fullscreen mode

As you can see above, we reduced an array by adding all of the values up into one, single number. If initial values is not provided, then array will take first element's value, and start iteration from the index of 1. If array is empty, then it will throw a TypeError stating Reduce of empty array with no initial value. Although if array only has only one element, then it will return an element, without calling the callback function.

Thanks for reading this post, if you found it helpful then feel free to leave a reaction and or follow for more posts like this, or tutorials on how to make different small things.

Discussion (0)