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)
Advertisement
Answer
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
- array: [8, 90, 0, 7]
- element: 8
- index: 0
- sum: 0
After calculating sum
- array: [8, 90, 0, 7]
- element: 8
- index: 0
- sum: 8
If we don’t return sum
after first iteration:
On the second iteration:
before calculating sum
- sum:
undefined
- array: [8, 90, 0, 7]
- element: 90
- index: 1
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
- sum:
undefined
+ 90 =NaN
- array: [8, 90, 0, 7]
- element: 90
- index: 1
So the value of sum
becomes NaN
So it continues to caluculate the value of sum
as NaN.