# JavaScript Average Function

Ammar Ali Oct 12, 2023

This article will discuss making a function to calculate the average of an array using a loop in JavaScript.

## Make a Function to Calculate the Average of an Array Using a Loop in JavaScript

There is no predefined function available in JavaScript to calculate the average of an array. We can make the function to get the average of an array using the average formula and a loop. To find the average of an array, we have to find the sum of all the elements present in an array using a loop and then divide the sum with the number of elements present in the array, which we can find using the `length` function. For example, let’s create the function to calculate the average of a given array and test it with an array and show the result of the average on the console. See the code below.

``````function ArrayAvg(myArray) {
var i = 0, summ = 0, ArrayLen = myArray.length;
while (i < ArrayLen) {
summ = summ + myArray[i++];
}
return summ / ArrayLen;
}
var myArray = [1, 5, 2, 3, 7];
var a = ArrayAvg(myArray);
console.log(a)
``````

Output:

``````3.6
``````

Using this function, you can also find the average of an array containing floating-point values.

Author: Ammar Ali

Hello! I am Ammar Ali, a programmer here to learn from experience, people, and docs, and create interesting and useful programming content. I mostly create content about Python, Matlab, and Microcontrollers like Arduino and PIC.