Your program does not work because a has the accumulated value from the previous function call. The first two values ββof the array will be used for the first time. So, sum will become 17 ( 2 + 15 ). Since you are not returning anything from the function, undefined will return by default and will be used as the value for a in the next call. So, the assessment is as follows
a: 2, b: 15 => 17 a: undefined, b: 7 => NaN
So, sum will have NaN , since undefined + 7 does it like this. Any numerical operation on NaN will always give NaN , so NaN / this.length gives you NaN . You can fix your program by simply returning the current value of sum whenever the function is called, so that the next time you call the function, a will have the proper accumulated value.
Array.prototype.average = function() { var sum = 0; this.reduce(function(a, b) { sum = a + b; return sum; }); return sum / this.length; };
But we do not use reduce power and flexibility here. Here are two important points to consider when using reduce .
reduce takes a second parameter, which indicates the initial value to be used. When possible, indicate this.
The first parameter in the function passed to reduce accumulates the result and finally will be returned, use this. There is no need to use a separate variable to track results.
So your code will look better than this
Array.prototype.average = function() { var sum = this.reduce(function(result, currentValue) { return result + currentValue }, 0); return sum / this.length; }; console.log([2, 15, 7].average());
reduce works like this. It iterates through the array and passes the current value as the second parameter of the function and the current accumulated result as the first parameter, and the value returned by the function will be stored in the accumulated value. So, the amount is actually found like this
result: 0 , currentValue: 2 => 2 (Initializer value `0`) result: 2 , currentValue: 15 => 17 result: 17, currentValue: 7 => 24
Since it has run out of values ββfrom the array, 24 will be returned as a result of reduce , which will be stored in sum .