How to find the average of an array of numbers in JavaScript
Calculating the average of number arrays is essential for statistical analysis, data visualization, performance metrics, and implementing features like grade calculators or analytics dashboards in JavaScript applications.
With over 25 years of experience in software development and as the creator of CoreUI, I’ve implemented average calculations in components like chart widgets, progress indicators, and data analysis tools where statistical computations provide meaningful insights for users.
From my extensive expertise, the most reliable approach combines array summation with length division using the reduce()
method.
This method handles edge cases like empty arrays while providing accurate floating-point results for statistical accuracy.
Sum the array elements with reduce()
and divide by the array length.
const numbers = [85, 90, 78, 92, 88]
const average = numbers.reduce((sum, num) => sum + num, 0) / numbers.length
// Result: 86.6
const getAverage = (arr) => arr.length ? arr.reduce((sum, num) => sum + num, 0) / arr.length : 0
// Usage: getAverage([10, 20, 30]) returns 20
The calculation combines two operations: reduce()
sums all array elements starting from 0, then divides by numbers.length
to get the arithmetic mean. In the example, (85 + 90 + 78 + 92 + 88) ÷ 5 = 433 ÷ 5 = 86.6. The function version includes a safety check using the ternary operator to return 0 for empty arrays instead of NaN
(which occurs when dividing by zero). This prevents calculation errors and provides predictable behavior for edge cases. The result is a floating-point number representing the average value.
Best Practice Note:
This is the same approach we use in CoreUI components for statistical calculations, data analysis features, and metrics displays across our component library.
Consider rounding results for display purposes using Math.round()
or toFixed()
. For large datasets, validate that the array contains only numbers to prevent NaN
results. The method works with integers, decimals, and mixed number types. Store the length in a variable if calling the function frequently to avoid repeated property access.