Open In App

JavaScript Program to Calculate the Average of All the Elements Present in an Array

Last Updated : 15 May, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array “arr” of size N, the task is to calculate the average of all the elements of the given array.

Example:

Input: arr = {1, 2, 3, 4, 5}
Output: 3
Explanation: (1+2+3+4+5) / 5 = 15/5 = 3

These are the following approaches:

Using for loop

This JavaScript program defines a function to calculate the average of elements in an array. It iterates through each element, sums them up, and divides the total by the number of elements. Finally, it returns the average value.

Example: This example shows the implementation of the above-explained approach.

Javascript
function calAvg(arr) {
    let sum = 0;
    for (let i = 0; i < arr.length; i++) {
        sum += arr[i];
    }
    return sum / arr.length;
}

const arr = [10, 20, 30, 40, 50];
const average = calAvg(arr);
console.log("Average:", average);

Output
Average: 30

Using a while loop

Here we define a function to calculate the average of elements in an array using a while loop. It initializes a sum variable, iterates through each element with an index variable, updates the sum, and finally divides it by the array length to compute the average.

Example: This example shows the implementation of the above-explained approach.

Javascript
function calculateAverage(arr) {
    let sum = 0;
    let i = 0;
    while (i < arr.length) {
        sum += arr[i];
        i++;
    }
    return sum / arr.length;
}

const arr = [10, 20, 30, 40, 50];
const average = calculateAverage(arr);
console.log("Average:", average);

Output
Average: 30

Using reduce() method

The approach sums array elements with reduce(), divides by array length for average. Utilizes reduce’s accumulator to compute total sum, then divides by array length to derive average value.

Example: This example shows the implementation of the above-explained approach.

JavaScript
let array = [10, 22, 16, 24];
let sum = array.reduce((acc, curr) => acc + curr, 0);
let average = sum / array.length;
console.log("Average: "+average);

Output
Average: 18


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads