Why does my reduce based average function return NaN?

Amir Rahbaran

Trying to get the average of an array.

Array.prototype.average = function() {
    var sum = 0;
    this.reduce(function(a, b) {
        sum = a + b;
    });
    return sum / this.length;
};

[2, 15, 7].average();

Why does the average function call return NaN?

thefourtheye

Your program didn't work because, a has the accumulated value from the previous function call. The first time, first two values of the array will be used. So sum will become 17 (2 + 15). Since you are not returning anything from the function, undefined will be returned, by default, and that will be used as the value for a, in the next call. So, the evaluation goes like this

a: 2,          b: 15   => 17
a: undefined,  b: 7    => NaN

So, sum will have NaN, since undefined + 7 makes it so. Any numeric operation on NaN, will always give NaN, that is why NaN / this.length, gives you NaN. You can fix your program, just by returning the current value of sum whenever the function is called, so that on the next function call, a will have 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 are not making use of the power and flexibility of reduce here. Here are two important points to consider when using reduce.

  1. reduce accepts a second parameter which says the initial value to be used. Whenever possible, specify that.

  2. The first parameter in the function passed to reduce accumulates the result and that will be returned finally, make use of that. No need to use a separate variable to keep track of the results.

So your code would look better like 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());
# 8

reduce actually works like this. It iterates through the array and passes the current value as the second parameter to the function and the current accumulated result as the first parameter and the value returned from the function will be stored in the accumulated value. So, the sum 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 ran out of values from the array, 24 will be returned as the result of the reduce, which will be stored in sum.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Java

Why does my recursive function return None?

From Dev

Why does my ajax function return false?

From Dev

Why does my recursive function return "undefined"?

From Dev

Why does my array element retrieval function return random value?

From Dev

Why does my generator function always return the same value?

From Dev

Why does my function not return value to global variable? [Python]

From Dev

Why does my generator function always return the same value?

From Dev

Why does my function not return the data I expect?

From Dev

Why does my Excel COUNTIF function always return a value of "0"?

From Dev

Why does my function not return value to global variable?

From Dev

Why does my dllimport function always return true?

From Dev

Why does my getColor function always return false?

From Dev

Why does my function return only one item that matches the criteria?

From Dev

Why does InterpolatedUnivariateSpline return nan values

From Dev

Why does 'valueAsNumber' return NaN as a value?

From Dev

Why does the Date class return NaN?

From Dev

Why does my API return {}

From Dev

Why is my "return" outside the function?

From Dev

Why does my GradientDescentOptimizer produce NaN?

From Dev

Why does [NaN].includes(NaN) return true in JavaScript?

From Java

Why does "noreturn" function return?

From Dev

Why does this function not return a value?

From Dev

Why does the function return false?

From Dev

Why does this function not return a value?

From Dev

Why does this function return zero?

From Dev

Why does my return statement ignore the rest of my code in a function in python?

From Dev

Weighted Average Reduce Function In CrossFilter

From Dev

why does (Function('return this'))(); return global?

From Dev

Why does my function not run?

Related Related

  1. 1

    Why does my recursive function return None?

  2. 2

    Why does my ajax function return false?

  3. 3

    Why does my recursive function return "undefined"?

  4. 4

    Why does my array element retrieval function return random value?

  5. 5

    Why does my generator function always return the same value?

  6. 6

    Why does my function not return value to global variable? [Python]

  7. 7

    Why does my generator function always return the same value?

  8. 8

    Why does my function not return the data I expect?

  9. 9

    Why does my Excel COUNTIF function always return a value of "0"?

  10. 10

    Why does my function not return value to global variable?

  11. 11

    Why does my dllimport function always return true?

  12. 12

    Why does my getColor function always return false?

  13. 13

    Why does my function return only one item that matches the criteria?

  14. 14

    Why does InterpolatedUnivariateSpline return nan values

  15. 15

    Why does 'valueAsNumber' return NaN as a value?

  16. 16

    Why does the Date class return NaN?

  17. 17

    Why does my API return {}

  18. 18

    Why is my "return" outside the function?

  19. 19

    Why does my GradientDescentOptimizer produce NaN?

  20. 20

    Why does [NaN].includes(NaN) return true in JavaScript?

  21. 21

    Why does "noreturn" function return?

  22. 22

    Why does this function not return a value?

  23. 23

    Why does the function return false?

  24. 24

    Why does this function not return a value?

  25. 25

    Why does this function return zero?

  26. 26

    Why does my return statement ignore the rest of my code in a function in python?

  27. 27

    Weighted Average Reduce Function In CrossFilter

  28. 28

    why does (Function('return this'))(); return global?

  29. 29

    Why does my function not run?

HotTag

Archive