skip to Main Content

I simply do this:

const ar = [1, 2, 3];
ar.reduce(Math.max, 0); // returns NaN
ar.reduce((a, c) => Math.max(a, c), 0); // returns 3 as expected 

Any reason for this behaviour?

2

Answers


  1. The callback function to Array#reduce is passed 4 arguments: the accumulator, the current element, the index, and the original array. All of these end up being passed to Math.max.

    The array itself cannot be converted to a number, so Math.max returns NaN.

    ar.reduce(Math.max, 0); is essentially equivalent to the following code:

    const ar = [1, 2, 3];
    console.log(ar.reduce((acc, curr, i, arr) => {
      console.log(acc, curr, i, arr); // only for demonstration
      return Math.max(acc, curr, i, arr);
    }, 0));

    ar.reduce((a, c) => Math.max(a, c), 0) uses only the arguments that it needs, so it works correctly.

    Login or Signup to reply.
  2. @Unmitigated has clearly explained what’s going on in your code and has shown how to use Array#reduce and especially Math#max.

    Here, I show you can use just Math#max:

    const 
          ar = [1, 2, 3],
          
          mx = Math.max(...ar);
          
    console.log( mx );
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search