Implement a function mean(array) that returns the mean (also known as the average) of the values in array, an array of numbers.
array (Array): The array of numbers.(Number): Returns the mean of the values in array.
mean([4, 2, 8, 6]); // => 5mean([1, 2, 3, 4]); // => 2.5mean([1, 2, 2]); // => 1.6666666666666667
The function should return NaN if array is empty.
mean([]); // => NaN
Computing the mean has two steps: add every value, then divide by the number of items. A common trap is to average too early or special-case empty arrays incorrectly. Every implementation keeps the same condition: after index i, total is the sum of all values from 0 through i.
for loopTrack a running total, then divide that total by array.length once the loop is done. The for loop version is the recommended one to internalize first because it makes both steps explicit.
The loop state has one job: preserve the exact sum of the values seen so far. The denominator does not change during the loop, so mixing division into the accumulation only adds rounding opportunities without making the algorithm simpler.
There is no "valid value" filter in this version. Every entry contributes to the total, and the denominator is always the original array length, including 0 and negative numbers.
For mean([4, 2, 8, 6]):
| Index | Value | total after adding |
|---|---|---|
0 | 4 | 4 |
1 | 2 | 6 |
2 | 8 | 14 |
3 | 6 | 20 |
The final answer is 20 / 4 = 5.
/*** @param {Array<number>} array* @returns {number}*/export default function mean(array) {let total = 0;// Calculate the sum of all numbers in the array.for (let i = 0; i < array.length; i++) {total += array[i];}// Calculate the mean from the sum.return total / array.length;}
Array.prototype.reduce()This version is shorter, but it is doing the same work: accumulate a total first, then divide by the array length.
export default function mean(array: Array<number>): number {return array.reduce((a, b) => a + b, 0) / array.length;}
0 / 0 evaluates to NaN, which matches the expected behavior.Infinity. That is beyond the normal scope of this interview question, but it is worth knowing that JavaScript numbers do not keep arbitrary precision for huge sums.console.log() statements will appear here.