Search code examples
if-statementconditional-statementsoperatorsconditional-operator

How to convert a ternary operator into a conditional operator?


Basically I need to transform a ternary operator into a conditional operator using "if...else" cycle.

function getBestStudent (students) {

const bestAverageMark = students.reduce((a, b) => getAverageMark(a) > getAverageMark(b) ? a : b)

return bestAverageMark
}

"getAverageMark" here is another function.

How can I transform this into a conditional operator "if... else"? Thank you!


Solution

  • you might wanna check out the mdn docs on arrow function expressions

    function getBestStudent (students) {
      const bestAverageMark = students.reduce((a, b) => {
         if (getAverageMark(a) > getAverageMark(b)) {
           return a;
         } else {
           return b;
        }
      });
    
      return bestAverageMark;
    }
    

    this could be simplified to

    function getBestAverageMark (a,b) {
      if (getAverageMark(a) > getAverageMark(b)) {
        return a;
      } else {
        return b;
      }
    }
    
    function getBestStudent (students) {
      return students.reduce(getBestAverageMark);
    }