DEV Community

Chiamaka Mbah
Chiamaka Mbah

Posted on • Updated on

How reduce() function really works

Unveiling the Magic of JavaScript's reduce() Function

Have you ever wondered how JavaScript's reduce() function works its magic? Today, we're going to pull back the curtain and explore the inner workings of this powerful tool. By the end of this article, you'll not only know how to use reduce(), but you'll also understand what's happening under the hood. Let's dive in!

What is reduce(), anyway?

First things first: reduce() is a higher-order function introduced in ES6 (ES2015). But what does that mean? Well, higher-order functions are like VIP functions – they get to hang out with other functions, taking them in as parameters or even returning them. Cool, right?

The Superpower of reduce()

So, what can reduce() do for you? Imagine you have a basket full of apples, and you want to know how many you have in total. reduce() is like your counting buddy, helping you turn that array of apples into a single number. It's not just for counting, though – reduce() can help you combine array elements in all sorts of creative ways!

How reduce() Works: A Visual Guide

Let's look at a simple example:

const numbers = [2, 3, 4, 5, 6];
const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
console.log(sum); // Output: 20
Enter fullscreen mode Exit fullscreen mode

But what's really going on here? Let's break it down:

  1. We start with an accumulator value of 0.
  2. For each number in our array, we add it to the accumulator.
  3. The accumulator keeps track of our running total.
  4. After we've gone through all the numbers, the accumulator gives us our final sum.

Peeking Under the Hood

Now, let's see what reduce() might look like if we wrote it ourselves:

function myReduce(array, callback, initialValue) {
  let accumulator = initialValue !== undefined ? initialValue : array[0];
  const startIndex = initialValue !== undefined ? 0 : 1;

  for (let i = startIndex; i < array.length; i++) {
    accumulator = callback(accumulator, array[i], i, array);
  }

  return accumulator;
}
Enter fullscreen mode Exit fullscreen mode

This function does the same job as the built-in reduce(). Let's break it down:

  1. We set up our accumulator, either with the initial value or the first array element.
  2. We loop through the array, starting from the appropriate index.
  3. For each element, we call our callback function, updating the accumulator.
  4. Finally, we return the accumulator with our result.

reduce() in Action: A Step-by-Step Breakdown

Let's walk through our earlier example, step by step:

  1. Start: accumulator = 0
  2. First round: 0 + 2 = 2 (accumulator is now 2)
  3. Second round: 2 + 3 = 5 (accumulator is now 5)
  4. Third round: 5 + 4 = 9 (accumulator is now 9)
  5. Fourth round: 9 + 5 = 14 (accumulator is now 14)
  6. Final round: 14 + 6 = 20 (accumulator is now 20)

And there you have it – 20 is our final result!

Wrapping Up

Now you know the secret behind reduce()'s power. It's not just about adding numbers – you can use this pattern to combine array elements in all sorts of creative ways. In our next post, we'll explore some real-world examples that go beyond simple arithmetic.

Remember, understanding how reduce() works under the hood isn't just about satisfying curiosity – it's about becoming a more informed and capable developer. So go forth and reduce with confidence!

Happy coding! ❤️🚀💻

Top comments (8)

Collapse
 
devhammed profile image
Hammed Oyedele • Edited

Are you sure that is how it truly works, what if my accumulator is not a number? do you know you can implement map and filter Array functions using reduce?

reduce

I think a better representation will be:

  function reduce (arr, fn, accumulator = 0) {
    arr.forEach((item, index) => {
      accumulator = fn(accumulator, item, index) // set the current accumulator value to the return value of the function
    })
    return accumulator
  }
Enter fullscreen mode Exit fullscreen mode

And welcome to Dev.together 🥰🥰🥰

Collapse
 
saucekode profile image
Chiamaka Mbah

Thank you for this but really I just wanted to let beginners see what the reduce() looks like behind the scene. But truly, thank you. 🤗

Collapse
 
homam profile image
Homam

Reduce is inherently an abstraction over recursion. It is the most generic operation that we can do with all arrays. Every other operation on arrays can be re-defined using reduce alone. Shameless plug: I wrote a little post about this concept Reduce.

Collapse
 
alfahim027 profile image
Al Masum Fahim

Good post. Waiting for your next post on the real life uses of reduce ().

Collapse
 
saucekode profile image
Chiamaka Mbah

Glad you liked it. Thank you.

Collapse
 
ypedroo profile image
Ynoa Pedro

Thank you, very helpful

Collapse
 
mirkan1 profile image
Mirkan

It was super usefull. Thanks alot

Collapse
 
saucekode profile image
Chiamaka Mbah

You're very welcome. Glad it was helpful.