Find the average of n numbers using JavaScript

featured Image

In this tutorial, we will learn how to find the average of the nth 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:

English Math Biology Chemistry Physics
75 80 90 60 70

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.

Alternative Method:

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

featured Image

Get the 10 characters from a string using JavaScript.

Here, in this article we will learn how to get the first 10 character from any string using JavaScript. Here we will be using JavaScript’s String method substring. What is…

Read more
featured Image

Convert date to long date format using JavaScript

In this article we will look into how to convert a date to a long date format using JavaScript. To convert it to a long format we will be using…

Read more
featured Image

Prevent body from scrolling when a modal is opened

Here, in this article, we will learn how to prevent the body from scrolling when a modal or a pop-up is opened using JavaScript. The scroll event is not cancelable….

Read more

Leave a Reply

Your email address will not be published. Required fields are marked *