[Solved] JavaScript reduce with ternary operator


Essentially, the code you provided is looping through each element in votes and checking whether it is greater than an element stored at a particular index. This index is stored in the variable bestIndex an is used to mark/keep track of the index which holds the largest element from all elements seen while looping.

In your example, your ternary is checking if a given element is larger than the currently marked biggest element (by doing v > arr[bestIndex]). If this is the case we then set the index of the current element to be the new position of the largest element (by implicitly returning i). If this is not the case, we leave the index of the largest element as it is by implicitly returning bestIndex.

You can translate this into a more procedural style of programming by using for loops and if-statements like so:

let votes = [-4, 10, 100, -3, 40];

let positionOfMax = 0;
for(let i = 0; i < votes.length; i++) {
  if(votes[i] > votes[positionOfMax]) {  // v > arr[bestIndex]
    positionOfMax = i; // ? i (from ternary)
  }
  /* Not needed
    else {posittionOfMax = positionOfMax} // : bestIndex (from ternary)
  */
}
console.log(positionOfMax);

I encourage you to take a look at .reduce() and the documentation on the conditional (ternary) operator. They’re both useful and powerful tools which can help speed up your development.

solved JavaScript reduce with ternary operator