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:

//An array of numbers that we want to get
//the average of.
var nums = [2, 10, 9, 6, 12, 3];

//Work out the sum of the numbers in
//our array
var totalSum = 0;
for(var i in nums) {
    totalSum += nums[i];
}

//Work out how many numbers are
//in our array.
var numsCnt = nums.length;

//Finally, get the average.
var average = totalSum / numsCnt;

//Print the median / average to the console.
//In this case, the average is 7.
console.log('Average is: ' + average);

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:

//JavaScript function that returns the average / mean
//value for all numbers in an array.
function arrayAverage(arr){
    //Find the sum
    var sum = 0;
    for(var i in arr) {
        sum += arr[i];
    }
    //Get the length of the array
    var numbersCnt = arr.length;
    //Return the average / mean.
    return (sum / numbersCnt);
}

An example of this function in action:

var arr = new Array(1, 2, 5, 20, 25);
var avg = arrayAverage(arr);
console.log(avg);

Hopefully, you found this post useful!