DEV Community

Cover image for Basics of switch cases and defaults
JkImExploring
JkImExploring

Posted on

Basics of switch cases and defaults

Switch cases were one of my favorite things to learn (and to use). Granted, they aren't always the best thing to use but when used I feel it makes the code cleaner than using if/else statements as well as slightly faster.

What is a switch case?

A switch case is a chunk of code that will perform differently depending on the result of the expression passed through.

The difference between the if/else statement and a switch is that in a switch statement you can continue to go through the statement even if one of the conditions is met. If not you can create a break statement.

Syntax:

(taken from w3schools)

switch(expression) {
  case x:
    // code block
    break;
  case y:
    // code block
    break;
  default:
    // code block
} 
Enter fullscreen mode Exit fullscreen mode

Example in practice:

var x = 2;

switch(x){
    case 0:
      console.log("Saturday");
      break;
    case 1:
      console.log("Sunday");
      break;
    default:
      console.log("You have to work.");
      break;
}
Enter fullscreen mode Exit fullscreen mode

This would return "You have to work." since the expression isn't equal to 0 or 1.

In comparison this is what the code looks like as an if/else statement:

var x = 2;

if (x==0){
   console.log("Saturday");
}
else if(x==1){
    console.log("Sunday");}
else{
   console.log("You have to work.");
}
Enter fullscreen mode Exit fullscreen mode

What should be the default?

I used to think it didn't matter but today I was working on the "Who likes it" kata on CodeWars and it clicked. The default is if it's equal to anything not previously covered.

For example, I had the default as if no one likes the status it will return "no one likes this." (which, harsh but okay.) However, it was failing on the attempt tests because where I had case 4 as listing any other number after 3 people liking it, that was only catching exactly 4 people. The switch statements only work for that number. They don't work for ranges as if/else statements can.

The solution to this was to make the return of "no one likes this" as a case 0.

Let me know if you have any questions below!

Top comments (2)

Collapse
 
jkimexploring profile image
JkImExploring

I've definitely noticed myself leaning on those when I know there are other ways to do what I need to do (especially working with arrays) so I've been trying not to lean on them as much. I think it's because it's clearer logic but I'm definitely going to go look at what you listed!