Calculating the mean / average in JavaScript.

This is a tutorial on how to calculate the mean / average of a JavaScript array. In this post, I have also included a custom function that will take in an array of numbers as a parameter and then return the average value.

Calculating the average.

To calculate the average number, we:

  1. Add up all of the numbers. This is called the sum.
  2. Count how many numbers there are.
  3. Finally, we divide how many numbers there are into the sum.

Example.

If we want to get the average of 1, 2 and 3, we start off by calculating the sum of those numbers:

1 + 2 + 3 = 6

The sum in this case is 6. After calculating the sum, we then count how many numbers there are.

In this case, we have 3 numbers.

That means that in order to get the average number, we must divide 3 into 6, which gives us 2.

6 / 3 = 2

Now, lets take the formula above and apply it to JavaScript.

Calculating the average / mean using JavaScript.

Take a look at the following example:

In the code above, we:

  1. Create a JavaScript array containing the numbers that we want to get the mean of.
  2. Calculated the sum by looping through the array using a for loop. Inside each iteration, we add the current number to our total sum.
  3. Retrieved the length of the array using the .length property.
  4. Finally, we calculated the average number by dividing the number of elements in our array into the summation figure that we worked out above.

Note that the code above may seem unnecessarily long-winded. However, I purposely wrote it that way so that novice developers can see what is going on, step by step.

Custom JavaScript function.

If you’re just looking for a custom JavaScript function that you can include in your project, then you can use the one below:

An example of this function in action:

Hopefully, you found this post useful!

Facebook Comments