First of all, your code is incorrect. Arrays have a starting index of 0
, not 1
. Furthermore, array.length
is one more than the last filled index (because the length is 1 based, and the array is 0 based. Yes, this is confusing.) So you're starting by not including the first item, and then also adding up an undefined item.
And what happens if you get an empty array? You divide by zero, which is MADNESS!! MADNESS I TELL YOU!
Second, there's a reason the code looks the same as everywhere: You have followed the definition of the average; the sum of components divided by the number of components. There's no shame in this, you should actually be proud that you've managed to conform to the standard.
If you really want, you can make the loop implicit. ES5 (ECMAScript 5, the latest js standard) defined an Array.prototype.reduce
function (click link for the reference.) It's a perfect fit for your needs, but doesn't change the core algorithm.
Third, your mean
function is doing something unexpected: Instead of just calculating the mean, it displays it as well. This does not follow expectations (or at least my expectation), as a function which calculates the mean should do that, and just that. That translates to a very important design aspect, which says that a function should do one thing, one thing only, and do it well. Because imagine if Math.sqrt
, for instance, starts displaying the square roots instead of giving you them. Like division by zero, it's madness all over again!