Exploring Reduce method : JavaScript

Well I went through a lot of blogs and articles to really understand what is reduce?. how it works? But somewhere it really didn't satisfied me. So let start with answering what is reduce method itself.

What is Reduce?

As you see the word reduce it self is used when you reduce something right so the reduce method itself reduces the given array to a single value. This single value can be a number, string or object.

So Lets Reduce. The first note is when to use reduce. So I would say for the start lets say you have array of number and you want to sum it up (basically you wanna reduce it one number right.)

So lets discuss how it actually works. The reduce method to the simplest form take two parameter.

The first parameter is a function, called as Reducer. This function is called for each value of the array. The second parameter is the starting value which will be used in the function. The reducer function itself than can take four parameter lets stick for two right now, the first one is the accumulator, basically its the thing that you be reducing the array to, and the second parameter will the current element in the array.

You can see in first parameter i.e function it takes two parameter here total is accumulator and list is the current value in the array. For the first iteration the total value is set to 0 as specified by the parameter.

If you are new in the JS world I would say it would be important to you if you analyse the map and filter method as well. They heavily overshadow reduce, making it look like the weirdo of the bunch. If you combine all this three things it will allow you to manipulate array however you want.

Reducer Function

As we discussed that the reducers function take upto 4 parameter. There are as follow:

  1. The accumulator
  2. The current value
  3. The index of the current iteration
  4. The array to operate on

Also in reduce method the second parameter is optional. If we don't initialise, it will take in the first value of the array. Hence the total value will be same. But its always a good practice to set the initial value. The reason is if we try to call an empty array with reduce method where initial value is not set it will throw an error.

Conclusion With reduce you must have know how ease it is to write code by eliminating all the for loops based code. Once you understand truly hoe reduce, map or filter works you can truly manipulate array however you want.

If you familiar with React and Redux now you can relate the Redux didn't came up with Reducers. It was always present but we never noticied it. ( I wanted to talk about reducers but was not able to fit it. Nonetheless until next time)

Thanks for reading.

- Vishak Amin