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.
Let get started with the coding part.
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);
What if the given value count is very large in number? And you don’t want to count it manually.
Output on Console average of an array using JS:
You might be wondering if you can code a Simple average function in JS that will take values as an input.
Well, let’s built a simple average function.
We will reuse the code which we have already built.
Encapsulate all the logic in a function.
Let’s name the function as average_value.[Answer]
Let’s have a set of values to be passed to the average function.
//array 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: