How reduce() function really works

Chiamaka Mbah - Aug 11 '19 - - Dev Community

Hello! New person alert! This is my first post on here and I am super excited.

Today, I will be explaining what the reduce() function really looks like under the hood so beginners in Javascript can truly understand how it works. It's not enough to just use it, I think it's also cool understanding how it works.

First of all, the reduce() function is a higher-order function. HIGHER-ORDER FUNCTIONS are functions that take in other functions as parameters. It was introduced in ES2015 or ES6.

WHAT DOES THE REDUCE() FUNCTION REALLY DO?

The reduce() function helps you turn an array of elements into a single value. In short, it sums up everything in an array. Cool, right? 😊

HOW IT WORKS

That's some code on how reduce() works but now I will be showing you how it truly works under the hood.

Ready. Set. Go!

Reduce() under the hood

That is an expansion of the reduce() function.

Now, I will break it down into chunks for your own understanding as to how this came to be. It's simple math and in Javascript, it is called Augmented Addition/Sum.

Breaking it into chunks

Remember we initialized accumulator to 0, it's the starting point of this entire code.

To Add:

accumulator += myArrayToBeSumed which also means... accumulator = accumulator + myArrayToBeSumed. (+=) this is augmented sum/addition.

A quick breakdown: the value on the left is accumulator while the value on the right is myArrayToBeSumed
=> 0 += 2 also means 0 = 0 + 2 answer is 2. Accumulator is now 2.
=> 2 += 3, 3 is the next element in the array. Accumulator is now 5.
=> 5 += 4, accumulator is now 9.
=> 9 += 5, accumulator is now 14.
=> 14 += 6, accumulator is now 20.

Accumulator keeps adding everything in the array until it gets to the last element in the array then it stops.

P/S: accumulator is just a name chosen for my variable, it is not a keyword in Javascript.

Next post hopefully would be on using the reduce() function in real-life examples, not just numbers.

Hope with this, you can understand how reduce() works under the hood and why you are using it. ♥️ ♥️ ♥️

. . . . . . .
Terabox Video Player