Hello! New person alert! This is my first post on here and I am super excited.
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.
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? 😊
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!
That is an expansion of the reduce() function.
Remember we initialized accumulator to 0, it's the starting point of this entire code.
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.
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. ♥️ ♥️ ♥️