Average with JavaScript
Tags: javascript, beginners, webdev, learning
Published: 2024-02-12 17:21:44

JavaScript 'objects' are simply containers of information. If we examine our LinkedIn profiles, we would find objects of ourselves staring back at us. I can transform my profile into an object and here is what it will look like:
 
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/au50c36a9d0iy4u3j3iq.png)

If I were to categorize different aspects of my life, I would need a few objects to paint the complete picture. I can then place all of those objects inside an Array. An Array in JavaScript is also an object too that stores a collection of multiple items. Think of an ‘array object’ as food storage container with a name on it, containing few more containers inside. If I use the example of my LinkedIn profile, I can place my personal information in one object and LinkedIn profile information in another. Then I can place all of that data in an Array with a name:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z3xl47eqaup3sbczerid.png)

Here is another example of an Array called ‘games’:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2edyutwga2uixjsnpbq6.png)

## Finding Average:

In the example above, we have a compilation of home team’s scores as well as opponent’s scores. In JavaScript, we can perform interesting mathematical operations that can manipulate numerical data, calculate complex equations, and enhance the overall functionality of our programs. We can use powerful tools to manipulate arrays and perform specific math operations to get the desired result. While I was learning about this, I came across the .forEach() iterator. ‘Iterators’ are tools that loop over an array of elements and inside their code blocks – because iterators are also functions – we can perform any kind of operation we desire.

In the example of ‘games’ array, I was learning to find the average of home team’s scores. To reach the average using .forEach() iterator, we first need a ‘starting point’. I am going to use a variable to set my starting point at zero:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ji74o0cogu5fym75qi8d.png)

In the code example above, I appended the .forEach() iterator with the games array to iterate or loop through its elements. Since we are only concerned with home team’s points, that’s what my ‘param’ or ‘parameter’ will add to the total score. To achieve that, I appended the ‘teamPoints’ to my function’s parameter.

To find the average after the .forEach() loop stops iterating, we need to divide the totalScore variable by the length of the 'games' array as per the formula for finding average of a set which is:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lis7qd84bh5mas0zxqu7.png)

where n is the total number of items in a set.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h3c3iv2mi8ri8qp0yeul.png)

## .reduce()

We can even make this simpler using a very powerful tool called the .reduce() method. With the help of this method, we can perform all of the calculations in one function and also avoid using an external variable.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/97au4fubamuqkqwtnxsi.png)

**.reduce()** has “reduced” the scores to one value, from which we can extract the average easily. The .reduce() method takes a callback function with four parameters, I have left out the last one, which is ‘array’. If we want to see what the ‘index’ parameter does, we can simple print the index to the console in the iterator’s code block:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uyxg4a6gbmc4pqkdhx1d.png)

We need to find the average after the loop ends and reaches the finish line, otherwise it won’t return the correct result. To find the average, we need to check if the ‘index’ has reached its end. If you print to the console all of the index numbers, the results will show:

0
1
2

And if we printed **games.length** to the console, the number will show 3. Which is why we want the math operation to work after the loop ends. The loop will end when index is equal to the length of the array minus 1, which will yield 2, since the end of the index is 2.

Just like the **startingPoint** variable for the **.forEach()** loop, we set the **accumulator** to 0, we can test the **accumulator’s** value by giving it another number than 0 and it will add that number to the reduction. So it acts like the **startingPoint** variable for the **.forEach()** loop. In case of operations like multiplication, the 0 initial value will multiply the numbers with 0 and return 0 as a result, which may not be desirable and cause unexpected errors. We also need to return the **accumulator** for every loop, so it has something to start from, otherwise for the second iteration, it will be undefined. If we don’t specify an initial value for the **accumulator**, the reduce function will take the first element of the array as the **accumulator**.

I wanted to check whether my loop was working correctly, which is why I only set the scores to the number divisible by 3, since we have 3 elements(objects) in our array. In case the average is a floating point value, we can always use Math.floor() to get a whole number. I can simple wrap the ‘result’ variable like so: 

```
result = Math.floor(result/games.length)
```

## Conclusion:

The **.reduce()** high-order function will take a callback function and return a single value. **.reduce()** is a very powerful tool and it has plenty of use cases. It can also be used to group values or remove duplicates and it is all thanks to the **accumulator**. If you have used **.reduce()** for you projects, share it with me. Thank you for reading, I am currently learning and started last year. Please let me know areas to improve and places for further reading and practicing. Thank you!