Why does my switch statement parameter require a boolean?

From my understanding, inside a switch statement parameter is supposed to be the item you are comparing against all your cases and returns the correct case.

My question is why does my switch statement require I put in the boolean true and not the "score" argument to which I am comparing all my cases? Thanks!

Heres the exercise

function convertScoreToGrade(score) {
  switch (true) {
    case (score > 100 || score < 0):
      return 'INVALID SCORE';
      break;
    case (score <=100 && score >= 90):
      return 'A';
      break;
    case (score <=89 && score >= 80):
      return 'B';
      break;
    case (score <=79 && score >= 70):
      return 'C';
      break;
    case (score <=69 && score >= 60):
      return 'D';
      break;
    case (score <=59 && score >= 0):
      return 'F';
      break;
  }
  return score;
}

1 answer

  • answered 2017-11-14 23:59 camel_case

    Because JS evaluates an expression in the parenthesis before it compares with the switch argument. Consider this example:

    convertScoreToGrade(71);

    function convertScoreToGrade(score) {
      switch (true) {
        case (false):
          return 'INVALID SCORE';
          break;
        case (false):
          return 'A';
          break;
        case (false):
          return 'B';
          break;
        case (true):
          return 'C';
          break;
        case (false):
          return 'D';
          break;
        case (false):
          return 'F';
          break;
      }
      return score;
    }
    

    Great explanation in this answer.