How to find the average of an array in JavaScript?

March 6, 2024

☕️ Support Us
Your support will help us to continue to provide quality content.👉 Buy Me a Coffee

In an entry-level JavaScript interview, array operation questions are often asked to ensure that applicants have basic JavaScript skills. Finding the average number of an array is among the most common questions. Given an array of numbers, such as [10, 20, 30, 40, 50], you need to write a function to calculate the average of this array.

This blog post provides two solutions:

  • for loop solution
  • Functional programming reduce solution

for loop solution

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

The logic of the above code is as follows:

  1. First declare a sum
  2. Iterate over the array through the for loop, and add up each number during the iteration process, and finally get the sum
  3. After adding up, divide the sum by the length of the array (the length of the array represents how many numbers are in the array), and you will get the average

Functional programming reduce solution

In the interview for this question, the interviewer may further ask you whether you know how to rewrite it using functional programming to test your functional programming skill. We can use the JavaScript's built-in array method reduce to do it:

  1. Iterate through each number of the array through reduce
  2. Add each currentValue during iteration to reduce to sum
  3. Finally, divide the result by the length of the array to get the average
const getAverage = (array) =>
  array.reduce((sum, currentValue) => sum + currentValue, 0) / array.length;
☕️ Support Us
Your support will help us to continue to provide quality content.👉 Buy Me a Coffee