How reduce works on JavaScript Arrays?

In this video we will learn what is reduce higher order function available as a method on JavaScript Arrays, why is it useful and how it works.


// Approach 01: Using forEach
let salaries = [2000, 4500, 2800, 6700, 7700, 4350];
let sum = 0;
sum = sum + element
// Approach 02: Using for..of
let salaries = [2000, 4500, 2800, 6700, 7700, 4350];
let sum = 0;
let iterator = salaries.values();
for(const value of iterator){
sum = sum + value;
// Approach 03: Using reduce() without initialValue
let salaries = [2000, 4500, 2800, 6700, 7700, 4350];
salaries.reduce((acc, cur) => acc + cur)
// Approach 04: Using reduce() with initialValue 0
let salaries = [2000, 4500, 2800, 6700, 7700, 4350];
salaries.reduce((acc, cur) => {
return acc + cur
}, 0)

Full Transcript

00:00 Hey, it's Deeksha Sharma from bonsaiilabs. Welcome to the series on JavaScript. Today, in this video, we will learn what is reduce() higher order function in JavaScript arrays, why reduce is useful and how it works? Let's say we have an array of salary numbers stored inside a variable called salaries. Our goal is to calculate the sum of elements in this array. One way of doing so is to have a sum variable which is initialized to zero. Then we will loop over every element in salaries array using forEach() method. This method takes as argument a callback function, which is executed on every element of salaries array. The job of the callback function is to keep adding the sum to the current element in the array. Now the sum variable keeps accumulating the total count, and once all the elements are traversed, the final value will be 28,050 which is the sum of all the elements.

00:51 Now another way to solve the same problem is to again have the sum variable initialized to zero, then called salaries.values() method, which returns an iterator containing the values at each index in the array. We store that inside an iterator variable. Now we use a for.. of loop to iterate over every value of the iterator. JavaScript provides a for..of statement to loop over the iterable objects such as arrays. Again, some variable keeps accumulating the sum of every value that finally sums up to 28,050 this is second way of summing up all the elements in the array. Finally, there is another way of adding up all the elements in the salaries array. This is by using reduce() higher order function. It is available as a method to JavaScript arrays. It gives the same results and does the same job in less code and has some benefits.

01:41 Don't worry about the syntax for now. We will cover that in detail in the next few minutes, but the reason I showed three ways to achieve the same objective is to demonstrate that there are different ways of solving a problem. All of them are correct. Using reduce() on arrays is just another way of summing up all the elements and that's the focus of this video. The purpose of reduce() method is to combine the elements in a sequence together and at the end gives us a reduced single value output. From the syntax standpoint, reduce() can be called on an array like this. reduce() is a higher order function, higher order functions are those that take other functions as input or return other functions as output or do both. The first argument to reduce is a function which is called reducer function, and the second argument is an optional initial value.

02:26 Now let's get into a bit more detailed syntax of reduce() method, reducer function accepts 4 arguments. The first one is the accumulator which accumulates the results of the execution from reducer function. The second is the current element in the array. That third is the index of the current element and the last one is the array itself that's being traversed. The last two arguments in the reducer function are optional. Let's consider the same example and our goal is to calculate the sum of all elements in salaries array. We called reduce() method and denote this reducer function with f(x). This reducer function executes every element of the array. Each time reducer function executes, the result is stored in the accumulator and the final single value of the accumulator is returned once all the elements in the salaries array are traversed. If you remember, we learned that reduce()method has two arguments - a reducer function and an optional initial value.

03:17 Now, if initial value is not supplied as an argument to the reduce() method, the accumulator grabs the first element in the array which becomes the initial value of the accumulator and the current value will be the second element of the array. But if you do provide the initial value argument to reduce() method, then accumulator starts with the initial value and the current value will be the first element in the array at index zero. Let's look at the step-by-step execution of the same example with no initial value. To calculate the sum of all the elements in salaries array we called reduce() method and only pass the first argument, which is the reducer function. Since there is no initial value. Accumulator grabs the first element in the array to start with, which is 2000 and the current value is the second element in the array 4,500 which means the reducer function starts executing from the second element in the array and after the execution, it returns the result of 6,500 which is the sum of accumulator and the current value.

04:11 From there onwards, accumulator will start accumulating the result which will be used in the subsequent executions. Finally, when all the elements in the array are finished, a single value output is returned, which is the total sum of 28,050. We will solve the same problem, but this time with an initial value, we call the reduce() method on salaries array, and since the arrow function is not in a single line anymore, we introduced the curly brackets with a return statement. We also added the second argument, initial value, which is zero. Since we have an initial value, accumulator starts with that and the current value is the first value in the array, which is 2000. Now this time execution of the reducer function starts from the first element in the array. It calculates and return the sum of accumulator and current value, which is zero plus 2000 and from here onwards, accumulator starts accumulating the return values for further executions.

04:59 Finally, after traversing all the elements inside salaries array, an output of 28,050 is returned. So this is the major difference in the usage of reduce() method with or without an initial value. Now the question comes in, why reduce or in general, why any higher order function including map(), reduce(), filter() or custom higher order functions ? The first one is very specific to the built-in higher order function on arrays that gives us immutability. Using map(), reduce() or filter() does not mutate the original array, but in general higher order function encourages and encapsulation of the common code into functional forms. For example, supporting reduction or filtering on arrays is a common operation, and so it's encapsulated as separate functions. They also help you write less code. We covered a few examples in the beginning of the video, and in fact, using reduce() method was the shortest way to get the same result. Higher order functions helps writing clear programs because the intent of the code is rather explicit than implicitly stated. I hope this video gave you a fair idea on what's the purpose of reduce() higher order function and how is it used. Thanks for watching, and as usual, if you have any questions, feel free to drop the comments. Don't forget to subscribe if you haven't already until then, keep learning and share your knowledge.