## JavaScript Average

If you are a JS programmer or just jumped into JavaScript average then you might need this basic arithmetic calculation in day to day programming needs().

In this article, I am gonna give you various examples of how we can find the average using JavaScript.

**What is Average?**

The average is simply the sum of all the values divided by the total number i.e count of values.

Thus, the average is the central value of a set of numbers.

## How to find JavaScript Average?

**Example 1: Find the average of 6 values using JavaScript : 40,55,89,45,63,12.**

[Answer] :

`var sum=0;`

var average=0;

sum=40+55+89+45+63+12;

console.log("The sum of six number is " + sum);

average=sum/6;

console.log("The average of six numebr is " + average);

Output on Console javascript sum and average:

What if the given value count is very large in number? And you don’t want to count it manually.

Then the JavaScript** length function** comes into play.

**Example2: Find the JavaScript average of an array**

[Answer]

`var values=[45,77,1,32,47,10,35,91,20,17,5,41];`

var i=0 , sum=0, average=0;

`console.log("Total count of values " +values.length);`

// simple loop to sum the value in a an array JS

for(i=0;i<values.length;i++)

`{`

sum=sum+values[i];

}

`console.log("Sum of all values " + sum);`

average=sum/values.length;

console.log("Javascript Average is "+average);

Output on Console average of an array using js:

You might be wondering if you can code a Simple average function in JS which will take values as an input.

Well, lets built a simple average function.

We gonna reuse the code which we have already built.

**Example 3: Simple average function in JavaScript**

Encapsulate all the logic in a function.

Let’s name the function as average_value.

[Answer]

`//function define`

function average_value(num){

var i=0 , sum=0, average=0;

var values;

values=num;

`console.log("Total count of values " +values.length);`

// simple loop to sum the value in a an array javascript

for(i=0;i<values.length;i++)

{

sum=sum+values[i];

}

console.log("Sum of all values " + sum);

average=sum/values.length;

console.log("Average is "+average);

}

Let’s have a set of value to be passed to the average function.

`//arry of number`

var num=[45,56,78,0,4,2,6];

Now we just need to pass the above value to the function and call it.

` var num=[45,56,78,0,4,2,6];`

//function call

average_value(num);

### Output on the console of the above simple JS average function:

I hope this information gonna help you out if you have searched for the solution to the problem. Please find the source code below.

Note: Try commenting and uncommenting the code in the source file if you are trying to run a particular example section.

Let us know your feedback in the comment section below and feel free to share. Peace!

Tags: javascript array, javascript average, javascript coding, javascript sum