Find the average of n numbers using JavaScript

javascript2 min read

Tutorial to write a JavaScript function to find the average of n numbers of items in an Array using JavaScript.

In this tutorial, we will learn how to find the average of the n<sup>th</sup> number of items in an array using JavaScript.

There is no built-in JavaScript function to find the average of numbers. However, we can just write a function knowing the mathematical formula of finding the average of a given set of numbers.

Mathematically,

average = (sum of all the values) / number of values

Let's say Jack received his report card and these are his marks:

EnglishMathBiologyChemistryPhysics
7580906070

So the average of the marks will be:

average = (75 + 80 + 90 + 60 + 70) / 5 (five subjects) average = 75

So, now let us write a JavaScript function to automate the process of finding the average easily.

The JavaScript function will take the N numbers of values of an array and it will return the average of the values.

function findAvg(arr){ let sumOfElement = 0; let totalNumOfElement = arr.length; arr.forEach(element =>{ sumOfElement += element }) return average = sumOfElement/totalNumOfElement } console.log('Average:', findAvg([75,80,90,60,70]))

Output:

Average: 75

Here, in the above code:

arr.length : gives us the total number of items.

we have used forEach() to loop through each item in the array and added the sum to the variable sumOfElement .

In the end, we have divided the total sum of the items by the total number of items to get the average as the return value.

<u>Alternative Method:</u>

We can also use for loop to do the same task as above.

function findAvg(arr){ let sumOfElement = 0; let totalNumOfElement = arr.length; for(i=0; i < totalNumOfElement;i++) { sumOfElement += arr[i] } return average = sumOfElement/totalNumOfElement } console.log('Average:', findAvg([75,80,90,60,70])) // Average: 75

So, this is how you can pass N numbers of values as a parameter to the function to return the average in JavaScript.

Related Articles:

How to find the median value of an array using JavaScript

Related Posts