This post will discuss how to calculate the average of all items in an array in JavaScript.

To find the average of all items in an array in JavaScript, we need to use a function that can sum up all the elements of the array and then divide the sum by the length of the array. There are several ways to do this, depending on the performance, readability, and compatibility of the code. Here are some of the functions that we can use, along with some examples:

1. Using a loop

This is a straightforward and intuitive way to iterate over the array and add each element to a variable that stores the sum. Then we divide the sum by the length of the array to get the average. Here’s an example using a for loop:

Download  Run Code

 
In this example, a for loop is used to iterate over each element of the array and calculate the sum of all elements. The variable sum keeps track of the running total. Finally, average is calculated by dividing the sum by the length of the array. This function is compatible with older browsers, but it may not be very elegant or concise.

2. Using reduce() function

The reduce() is a built-in function that applies a function that accumulates a single value from the elements of the array. It does not modify the original array. We can use it to find the average of an array by passing a function that adds the current element to an accumulator and then divides the result by the length of the array. Here’s an example:

Download  Run Code

 
In this example, arr.reduce((accumulator, currentValue) => accumulator + currentValue, 0) calculates the sum of all items in the array. The reduce() function applies the provided function to each element of the array and reduces it to a single value. The initial value of the accumulator is set to 0. Then, average is calculated by dividing the sum by the length of the array. This function is simple and elegant, but it requires ES6 support or a polyfill for older browsers.

3. Using Array prototype

Finally, we can add the custom functions Array prototype.sum() and Array.prototype.average() to the Array prototype to calculate the sum and average of an array. The sum function uses the reduce function to return the sum of all elements in the array. The average function uses the sum function and divides it by the length of the array. Here’s an example:

Download  Run Code

 
These functions are concise and expressive, but they also require ES6 support or a transpiler for older browsers. They also modify the Array prototype, which may cause conflicts with other code.

That’s all about calculating the average of all items in an array in JavaScript.