Reduce function in 10 minutes
Reduce function in 10 minutes

Reducer is a method that scares people most when they start learning JavaScript. In 10 minutes you will master it.

What reduce does it that it's a way to write your code not in imperative way but in declarative.

Let's say that we have an array of users and we want to sum their age.

const users = [
  { id: 1, name: "Jack", age: 20 },
  { id: 2, name: "John", age: 30 },
  { id: 3, name: "Mike", age: 35 },

let total = 0;

users.forEach((user) => {
  total = total + user.age;


So here we created a variable total and used forEach loop to take age from each user and add it. This code has several problems.
First of all such code is written in imperative way, which means we write how it should be be done and not what should be done.
Secondly we must create total property before outside of our forEach and it's completely unrelated to our code.
And lastly we override total property every time while looping.

Let's rewrite this with reduce to see the difference.

const total = users.reduce((acc, user) => {
  console.log("reduce", acc, user);
  return acc;
}, 0);

So we call reduce on our array. Reduce gets 2 parameters. The first one is a function which will be called on every element and the starting value of our accumulator. So what is accumulator? It's our result at the end. The idea is that we set the default value of it and we must return it every time when we work with each element.

As you can see in console we logged acc and user. User gives us access to every element in array and our accumulator is zero because we didn't change it. So how do we change it? We need to return new accumulator inside a function.

const total = users.reduce((acc, user) => {
  console.log("reduce", acc, user);
  return acc + user.age;
}, 0);

So we take accumulator and add user.age to it. As you can see in browser now on every element our accumulator changes. And at the end we get our total.

So what are benefits of reduce compared to forEach that we wrote earlier?

  • It's declarative and not imperative. Which means we describe what we want to do and not how we should it it.
  • We don't need to create properties before. We put the result directly in total variable which means our code is easy to read and it's all at one place
  • Our code is fully immutable because we just return the new accumulator value every single time.

Why is reduce so important? With foreach loop we can implement anything like map, filter, find, sum and much more. Literally anything with arrays transformation. Reduce is the same low level tool like for each but in functional, immutable and safe way.

Also if you want to improve your programming skill I have lots of full courses regarding different web technologies.