This JS code finds the index of the highest value in an array but how does it work?

The line of code in quesion:

let largest = arr.reduce((a,v,i) => v > a[1] ? [i,v] : a, [-1,0]);

I am confused mainly by this part a, [-1,0], I don’t understand this syntax. What is a doing before a comma?

Answer

Here’s how it looks with a lot of the shorthand expanded:

const reducer = (accumulator, currentValue, index) => {
  if (currentValue > accumulator[1]) {
    return([index, currentValue])
  } else {
    return(accumulator)
  }
}

let largest = accumulator.reduce(reducer, [-1, 0])

What’s happening:

Array.prototype.reduce() has two arguments, the callback function and the initial value. That’s where the [-1, 0] is coming from, that’s the “initial value” that will be passed as the “accumulator” to the callback function on the first iteration.

The shortest shorthand for a function in javascript is () => value where “value” represents the return value of the function—no parenthesis are required. In this example that return value is a ternary statement: condition ? return if true : return if false. Essentially, because they’re using a single line to produce a single value, there’s no parenthesis or braces required around the function.

The callback function you pass to Array.reduce() can take three arguments, (accumulator, currentValue, index).

The key here is in the initial value, which is [index, value], which keeps track of both until iteration is finished, in which case just the final value is returned.