Why Nan’s reduce return?

Asked

Viewed 58 times

-2

I commented on Re-turn sum, on purpose, because I didn’t understand. If I remove Return sum, it returns the right average, I do not understand when it enters the if in the last position this return shows Nan. But why returns 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)
  • 4

    Related: https://answall.com/q/480776/69296

1 answer

-4


The Return inside the IF will only work in the last element. All the above will be Undefined. Leaving Undefined + the last value = NAN. And in the last iteration it will enter if and return Undefined + the sum.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.