Average of numbers in array using JavaScript
In this tutorial, you are given an array of numbers. Write a JavaScript program to find the average of these numbers in array.
Solution
To find the average of numbers in array, first find the sum using a for loop and iterating over the elements of array, and then divide the sum with the length of the array.
Program
In the following program, we are given an array of numbers in nums
. We shall find the average of these numbers in the array.
let nums = [4, 8, -3, 41, 2, 0, 6];
let sum = 0;
for (let index = 0; index < nums.length; index++ ) {
sum += nums[index];
}
let average = sum / nums.length;
console.log(average);