Reputation: 5
I commented out the return sum
, on purpose, because it does not work as expected.
If I remove return sum, it returns the right average. But this is what I don't understand: when it enters the if in the last index position, this return shows NaN.
But why does it return NaN?
const mediaNumeros = numeros.reduce((sum, element, index, array) => {
sum = sum + element;
if (index == array.length - 1) {
return Number((sum / array.length).toFixed(2));
}
// return sum;
}, 0)
Upvotes: 0
Views: 114
Reputation: 204
Let us assume the value of numeros be [8, 90, 0, 7]
Let's see what's going on in each iteration:-
On the first iteration:
before calculating sum
After calculating sum
If we don't return sum
after first iteration:
On the second iteration:
before calculating sum
undefined
NOTE: Array.prototype.reduce() accepts a function (i.e it is higher order function) and not a loop.
sum
becomes undefined as we did not return the value of the previous function call . Js engine has no idea what is the value of sum
as the previous function has finished and its execution context is deleted.
After calculating sum
undefined
+ 90 = NaN
So the value of sum
becomes NaN
So it continues to caluculate the value of sum
as NaN.
Upvotes: 2