The `reduce()` Method in JavaScript
A Must-Know JavaScript Array Method that’ll Save Your Life
The reduce()
method in JavaScript is one of the most commonly used and efficient methods that can save you hours when working on your project. This method can be a powerful replacement for the loops we have in JavaScript.
Loops take a long time plus space in your code environment, while the reduce()
method can be both low in space and easy to use.
So let’s learn this amazing and life-saving method the right way…
To illustrate the functionality of reduce()
method, let’s have a real-life illustration.
Imagine you have a lot of coins and want to find out how many coins are there. You could count them one by one, but it’ll take a long time before you reach the final one. Instead, you could use a special machine to count them faster. This machine is called the reduce() machine.
You spill all of the coins into the machine, and the machine starts counting them. It takes two coins at a time, adds them together, and gives you the result. Then it takes the next two coins, adds them to the previous result, and gives you a new value. It keeps doing this until it has gone through all the coins and given you the final result, which is the total of all the coins.
The reduce()
method functions just like that; it takes two arguments: a function as its first argument and an initial value as its second argument. But instead of coins, it takes an array of numbers.
The function takes two numbers at a time, combines them, and gives you the result. Then again, it takes the next two numbers, combines them with the previous value, and gives you a new result. It keeps doing this until it has gone through all the numbers in the array and given you the final result as a single number.
Here’s a basic example of how the reduce()
method works:
In the example above, the reduce()
method starts with an initial accumulator value of 0 (as long as no initial value is defined) and iterates over each element in the number array. The accumulator function adds the current value to the accumulator and returns the result, which becomes the new accumulator value for the next iteration until all the elements in the array have been processed.
When the accumulator
is 1 and the currentValue
is 2, the function returns 3 as a result. The value of accumulator
has been updated to 3. Then in the next iteration, as the accumulator
is 3, the currentValue
is 3 as well (the last element in the array is 3). Now the accumulator
(3) and the currentValue
(3), if combined, is equal to 6 as the final result.
Don’t forget to visit my Medium blog. 💛
Happy Coding :)