DEV Community

Urooba
Urooba

Posted on

Average with JavaScript

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

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

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

Image description

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

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

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

Image description

.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

.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

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)
Enter fullscreen mode Exit fullscreen mode

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!

Top comments (4)

Collapse
 
hriztam profile image
Hritam Shrivatava

Excellent post

Collapse
 
faiq157 profile image
Faiq Ahmad

Interesting 🙌

Collapse
 
best_codes profile image
Best Codes

Great post, thanks for sharing!

Collapse
 
uroobacodes profile image
Urooba

I had no idea I received comments! Wow! Thank you so much for reading. I am only just starting out so these comments are quite encouraging. 🙌