DEV Community

loading...

Using the Switch Statement with Logical Operators

Jasterix
Passionate about building great technology and connecting with people to create positive change. Happy to answer questions about transitioning to tech. Find me on Twitter @lounecl
Updated on ・2 min read

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.

Discussion (4)

Collapse
merri profile image
Vesa Piittinen

You don't need a break if you return :)

Collapse
jasterix profile image
Jasterix Author

good point. I'll update the code to reflect this

Collapse
xowap profile image
Rémy 🤖

What is the advantage of this syntax over if/elseif?

Collapse
jasterix profile image
Jasterix Author • Edited

I decided to use it here to get more practice with switch statements, but in this scenario, if/else would be more appropriate

this article explores when to use if/else vs a switch statement

Forem Open with the Forem app