How to Find Average of Array Elements in JavaScript

To find the average of array elements in JavaScript, you need to follow these steps:

  1. Calculate SUM of values of all the elements in an array
  2. Divide the SUM with total nember of elements (length of array)

There are multiple options to find JavaScript average of array. However, we can use for...in loop but it's important to note that the for...in loop in JavaScript is generally used to iterate over the enumerable properties of an object, not recommended for iterating through arrays due to potential issues like iterating over prototype properties and iterating in a non-guaranteed order. Instead, the for...of loop or array iteration methods like forEach(), reduce(), or a simple for loop are typically recommended for arrays.

In this step-by-step tutorial, you will learn how to calculate js average of array elements using following three methods:

  1. Using reduce method
  2. Using forEach() method
  3. Using for...of loop

Option 1: JavaScript Average of Array Using reduce() Method

Finding the average of JavaScript array using reduce() function involves summing up all the elements in the array and dividing the sum by the total number of elements.

Step 1: Create an Array of Numbers

Let us start by defining an array containing numbers you want to find the average.

const numbers = [10, 15, 20, 25, 30]; 

Step 2: Use reduce() Method

The reduce() method is used to iterate through the array and accumulate a single value, in this case, the sum of all elements.

const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0); 

Here:

  • accumulator is the accumulated value that starts with an initial value of 0.
  • currentValue represents the current element being processed in the array.
  • accumulator + currentValue performs the addition of each element to the accumulator.

Step 3: Calculate the Average

Once you have the sum of all elements, you can calculate the average by dividing the sum by the total number of elements in the array.

const average = sum / numbers.length; 

Here numbers.length gives you the total number of elements in the array.

Step 4: Display the Average

Finally, you can display or use the calculated average as needed.

console.log('The average is:', average); 

Complete Example:

Putting it all together:

// Step 1: Create an Array of Numbers 
const numbers = [10, 15, 20, 25, 30]; 

// Step 2: Use the reduce() Method to Calculate the Sum 
const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0); 

// Step 3: Calculate the Average 
const average = sum / numbers.length; 

// Step 4: Display the Average 
console.log('The average is:', average); 

Notes:

  • Ensure the array contains valid numeric values for accurate averaging.
  • The reduce() method is a powerful tool that can perform various operations on arrays by accumulating values. Understanding its functionality can be beneficial for handling array operations efficiently.

Option 2: JavaScript Average of Array Using forEach() Method

Calculating the average of elements in an array using the forEach() function in JavaScript involves iterating through the array, summing up all the elements, and then dividing the sum by the total number of elements.

Step 1: Create an Array of Numbers

Let us start by defining an array containing numbers you want to find the average.

const numbers = [10, 15, 20, 25, 30]; 

Step 2: Initialize Variables for Sum and Count

Create variables to keep track of the sum of elements and the count of elements in the array.

let sum = 0; let count = 0; 

Step 3: Use the forEach() Method to Iterate Through the Array

The forEach() method is used to loop through the array and perform an operation on each element, in this case, adding each element to the sum and incrementing the count.

numbers.forEach((number) => { 
  sum += number; // Add the current number to the sum 
  count++; // Increment the count of elements 
}); 

Step 4: Calculate the Average

Once you have the sum of all elements and the count of elements, you can calculate the average by dividing the sum by the total count.

const average = sum / count; 

Step 5: Display the Average

Finally, display or use the calculated average as needed.

console.log('The average is:', average); 

Complete Example:

Putting it all together:

// Step 1: Create an Array of Numbers 
const numbers = [10, 15, 20, 25, 30]; 

// Step 2: Initialize Variables for Sum and Count 
let sum = 0; let count = 0; 

// Step 3: Use the forEach() Method to Calculate the Sum and Count 
numbers.forEach((number) => { 
  sum += number; // Add the current number to the sum 
  count++; // Increment the count of elements 
}); 

// Step 4: Calculate the Average 
const average = sum / count; 

// Step 5: Display the Average 
console.log('The average is:', average); 

Notes:

  • The forEach() method is a way to iterate through each element of an array and perform a function for each element.
  • Ensure the array contains valid numeric values for accurate averaging.
  • Using forEach() can be a simple way to perform operations on each element in an array and is useful for beginners to understand array manipulation in JavaScript.

Option 3: JavaScript Average of Array Using for...of Loop

Utilizing the for...of loop is a straightforward way to iterate through arrays in JavaScript and find the average of its elements.

Step 1: Create an Array of Numbers

Start by defining an array containing numbers you want to find the average.

const numbers = [10, 15, 20, 25, 30]; 

Step 2: Initialize Variables for Sum and Count

Create variables to keep track of the sum of elements and the count of elements in the array.

let sum = 0; let count = 0; 

Step 3: Use a for...of Loop to Iterate Through the Array

The for...of loop is used to iterate through the array and accumulate the sum of its elements.

for (const number of numbers) { 
  sum += number; // Add the current number to the sum 
  count++; // Increment the count of elements 
} 

Step 4: Calculate the Average

Once the sum of all elements is obtained and the count of elements is known, calculate the average by dividing the sum by the total count of elements.

const average = sum / count; 

Step 5: Display the Average

Finally, display or use the calculated average as needed. 

console.log('The average is:', average); 

Complete Example:

Putting it all together:

// Step 1: Create an Array of Numbers 
const numbers = [10, 15, 20, 25, 30]; 

// Step 2: Initialize Variables for Sum and Count 
let sum = 0; 
let count = 0; 

// Step 3: Use a for...of Loop to Calculate the Sum and Count 
for (const number of numbers) { 
  sum += number; // Add the current number to the sum 
  count++; // Increment the count of elements 
} 

// Step 4: Calculate the Average 
const average = sum / count; 

// Step 5: Display the Average 
console.log('The average is:', average); 

Notes:

  • The for...of loop simplifies the iteration process by directly accessing each element in the array.
  • Ensure the array contains valid numeric values for an accurate average calculation.
  • Understanding how to use a for...of loop for array iteration is fundamental in JavaScript and provides a cleaner and more concise way to work with arrays.
  • Utilizing a for...of loop to iterate through an array and perform calculations, such as finding the average, is a beginner-friendly and effective method in JavaScript programming.

JavaScript Function to Calculate Average of Array

As a best practice for code reusability and readability here is a simple JavaScript function to calculate the average of elements in an array:

function arrAverage(arr) {
    if (arr.length === 0) {
        return 0; // Return 0 if array is empty
    }

    // Calculate the sum of all elements in the array
    const sum = arr.reduce((accumulator, currentValue) => {
        return accumulator + currentValue;
    }, 0);

    // Calculate the average
    const avg = sum / arr.length;

    return avg;
}

// Example usage:
// Array of Numbers
const arr = [10, 20, 30, 40, 50];
const avg = arrAverage(arr);
console.log('Average:', avg); // Output: 30

Explanation:

  • The arrAverage function takes an array arr as its parameter.
  • It first checks if the array is empty and returns 0 if it is.
  • It then uses the reduce method to sum up all elements in the array.
  • After getting the sum, it divides it by the number of elements in the array to calculate the average.
  • Finally, it returns the average value.

Related articles and courses:

Article: JavaScript Array Iteration methods

Course: FREE JavaScript Course for Beginners