Using the Switch Statement with Logical Operators

Jasterix - Aug 18 '19 - - Dev Community

JavaScript's switch statement is a pretty powerful tool, but one I've generally avoided because it's not as predictable as if statements or the ternary operator. But while working through Codesmith's CSX challenges, I set my mind to using switch for one of the problems and learned something interesting in the process.

This is the challenge:

Create a function gradeCalculator which takes a grade (number) and returns its 
letter grade.

grades 90 and above should return "A"
grades 80 to 89 should return "B"
grades 70 to 79 should return "C"
grades 60 to 69 should return "D"
59 and below should return "F"
Enter fullscreen mode Exit fullscreen mode

Below is my initial solution:

function gradeCalculator(grade) {
  switch (grade) {
    case (grade >= 90):
      return "A"
    case grade >= 80:
      return "B"
    case grade >= 70:
      return "C"
    case grade >= 60:
      return "D"
    case grade <= 59:
      return "F"
  }
}
Enter fullscreen mode Exit fullscreen mode

Can you spot the mistake? At first, I couldn't understand why the terminal returned

undefined
undefined
undefined
undefined
undefined
Enter fullscreen mode Exit fullscreen mode

But a quick Google search brought me to a StackOverflow discussion that addressed the issue.

The Answer

Basically, JavaScript is trying to compare the expression in the parentheses to the values of the cases.

If grade = 92, grade >= 90: would return true, but I had my switch statement to comparing true to grade (or 92). True === 92 returns undefined

The proper way to formulate my switch statement is:

function gradeCalculator(grade) {
  switch (true) {
    case (grade >= 90):
      return "A"
    case grade >= 80:
      return "B"
    case grade >= 70:
      return "C"
    case grade >= 60:
      return "D"
    case grade <= 59:
      return "F"
  }
}
Enter fullscreen mode Exit fullscreen mode

Check out the StackOverflow discussion here.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player