Software, Tech & Coding simplified.

JavaScript How to Calculate Average of an Array

To calculate the average of an array in JavaScript:

  1. Sum all the values of the array.
  2. Divide the sum by the length of the array.

For example:

const arr = [1, 2, 3, 4, 5];
const average = arr.reduce((a, b) => a + b, 0) / arr.length;

console.log(average);

Output:

3

This is the quick answer.

However, if this does not ring any bells, I recommend reading further.

In this guide, you learn how to calculate the average of an array of numbers in three different ways:

  1. The for loop approach
  2. The forEach() function
  3. The reduce() function

Before jumping into these, let’s make sure you understand what it means to calculate the average in the first place.

Average in Mathematics

The average value describes the centrality of data. Here the red line is the average height of the columns.

In mathematics, the average is the middle value of a group of numbers. The average is also commonly called the mean or the arithmetic mean.

The average is calculated by dividing the sum of all the values by the number of values.

Example. Find the average age of a group of students in this table:

NameAge
Alice32
Bob25
Charlie23
David24
Eric26

Solution. Let’s sum up the ages and divide the result by the number of students:

s = 32 + 25 + 23 + 24 + 26 
  = 130

n = 5

avg = s / n
    = 130 / 5
    = 26

Calculating the average is a useful way to describe data in statistics.

For instance, you can calculate the average of your grades to get an idea of how well your studies are going.

Anyway, let’s jump into the coding part of this tutorial.

Let’s implement a basic JavaScript for loop to find the average first.

Find the Average with For Loop in JavaScript

Perhaps the most beginner-friendly way to find the average of a JavaScript array is by using a for loop for summing up the numbers.

Here is how to use a for loop to find the average of an array of numbers:

  1. Create an array of numbers.
  2. Initialize the sum variable to accumulate the numbers.
  3. Loop through the numbers and add each number to the sum.
  4. Divide the sum of numbers by the number of numbers in the array.
  5. Show the result.

For example:

const arr = [1, 2, 3, 4, 5];

var sum = 0;

for (var number of arr) {
    sum += number;
}

average = sum / arr.length;

console.log(average);

Output:

3

Although there is nothing wrong with this approach, we can make it way shorter and more concise.

Next up, you are going to learn how to use the forEach() function for calculating the average.

The following examples are more intermediate. Do not worry if you find them a bit tricky as a beginner!

Find the Average Using forEach()

In JavaScript, there is a built-in function called forEach().

This function is used to run a give function for each element in the array.

In other words, the forEach() function behaves a lot like a for loop. It iterates through the array and calls the given function for each element.

To find the average using forEach() function:

  1. Create an array of numbers.
  2. Initialize the sum to 0.
  3. Use forEach() function to loop through the numbers and add each number to the sum.
  4. Divide the sum of numbers by the number of numbers in the array.
  5. Show the result.

To make the forEach() add each number to the sum, it needs to take a function that accepts a number argument and adds it to the sum.

For example:

const arr = [1, 2, 3, 4, 5];

var sum = 0;

arr.forEach(function(num) { sum += num });

average = sum / arr.length;

console.log(average);

Output:

3

To make it a bit more concise, you can also use the arrow function notation in the forEach() function call:

const arr = [1, 2, 3, 4, 5];

var sum = 0;

arr.forEach((num) => { sum += num });

average = sum / arr.length;

console.log(average);

Although this approach is a bit shorter than the for loop approach, it is still not the most elegant one.

Next, let’s use the reduce() function to find the average of an array of numbers.

This will make the process significantly more straightforward.

Find the Average Using reduce()

In JavaScript, there is a built-in function called reduce().

This function works the same way as folding in mathematics. Reducing means you fold a group of numbers into a single value.

For example, you can reduce or fold an array of numbers to get the sum of it.

The reduce() function takes a function as its argument. This is called a reducer.

It also takes an initial value for the accumulated result as its second argument.

Here is how the reduce() function and the reducer function operate on an array:

  1. Call a reducer on the first two elements of the array to get a partial result.
  2. Call the same function on the partial result and the third element of the array to create a new result.
  3. Repeat until there are no more values left.
  4. Return the result.

Now, let’s use the reduce() to find the average of a function.

For example:

const arr = [1, 2, 3, 4, 5];
const average = arr.reduce((a, b) => a + b, 0) / arr.length;

console.log(average);

Output:

3

Let’s take a moment to understand how this piece of code works:

  1. The reducer (a, b) => a + b is called for each number in the array, where
    • a is the “result so far”.
    • b is the next number.
  2. The second argument of the reduce() function call is 0. This is the initial value for the sum of the array.
  3. The reduce() function is used to find the sum of the numbers in the array.
  4. The sum is then divided by the length of the array to get the average.

As you can see, this piece of code is way shorter than the for-loop approach. Once you learn how to read the reduce() function a bit better, you notice how much simpler this piece of code is than the lengthy for loop.

To find a complete guide on how to use the reduce() function in JavaScript, feel free to read this article.

This completes the example.

Now you should have a great understanding of how to calculate the average of an array in JavaScript in a bunch of different-looking ways.

Before you go, let’s do a quick recap.

Conclusion

Today you learned how to calculate the average of an array in JavaScript.

To recap, the average is used in statistics to describe the centrality of a dataset.

To find the average (the mean), sum up the values and divide the sum by the number of values.

In JavaScript, there is a bunch of ways in which you can find the average. In this guide, you saw three common examples:

  • For loop
  • The forEach() function
  • The reduce() function.

The latter approach is a bit tricky to wrap your head around as a beginner. However, it is a really short and concise way to get the job done.

Thanks for reading.

Happy coding!

Further Reading

JavaScript Interview Questions

Share

Share on twitter
Share on linkedin
Share on facebook
Share on pinterest
Share on email