Suggestion, none of the answers here check for length === 0, you'll be dividing by zero in some situation in the future. I suggest you always check mathematical boundary conditions. The related article had one response which caught that (https://stackoverflow.com/a/18234568/987044).
Here is another example if you want to be safe.
http://jsfiddle.net/ledlogic/syn74/
var nothing = null;
var empty = [];
var items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]; // 20 sider
function average(items) {
if (!items) {
return 0;
}
var sum = 0,
count = 0;
// for large arrays, faster to go down.
for (var count = items.length, i = count - 1; i >= 0; i--) {
sum += items[i];
}
return count ? sum / count : 0;
}
alert(nothing + ":" + average(nothing) + "\r" + empty + ":" + average(empty) + "\r" + items + ":" + average(items) + "\r");
The math.js library, mean.js also does array length checking.