DEV Community

Cover image for Switch to Switch Statement?
Kass M
Kass M

Posted on

Switch to Switch Statement?

*Not-so-fun fact:
You CAN NOT use logical operators in the switch case statements.
*

A switch statement can be seen as an alternative to an if-else statement. Comparing switch-case and if-else statements, their differences only show when dealing with a large set of selections; in these cases, the switch statements will prove to have faster processing power due to their fixed depth structure. Switch statements are also easier to debug and maintain. Though switch statements can get lengthy, their fixed depth makes it easy to spot and manipulate problem areas.

For example: If you want to change the wake-up time for Thursday in the code below, you would have to restructure the if-else statement slightly.
Image description

But, when dealing with a switch statement, you would only need to locate the "Thursday" case and make the immediate change.
Image description

When deciding between if-else and switch-case, always consider how many options you will be working with, if changes in the code might be necessary over time, and how fast you need the processing speed to be.

*Bonus Fact!
Once your switch statement finds its match case, it will print out everything from there and down unless a break is indicated.
*

No breaks:
Image description
Breaks:

Image description

--Thank you for reading my first post! Feel free to comment and follow. I'm here to learn just as much as I am here to share my findings through my journey to becoming a software engineer.

Top comments (9)

Collapse
 
tqbit profile image
tq-bit • Edited

Hi Kass,

congratulations on your first post :) I'm looking forward to read more from you.

If you're dealing with big or more complex structures, a neat alternative to classic if-else statements or switch are hash maps. You can use them to separate your data structure from processing logic.

I've replicated your example to give you an idea:

const week = {
    monday: { alarm: '4am' },
    tuesday: { alarm: '6am' },
    wednesday: { alarm: '6am' },
    thursday: { alarm: '6am' },
    friday: { alarm: '4am' },
    saturday: { alarm: 'sleep in' },
    sunday: { alarm: 'sleep in' },
};

let day = 'thursday';
console.log(week[day].alarm);
Enter fullscreen mode Exit fullscreen mode

Happy coding!

PS: I hate to be that guy, but the if-else statements should be if(day === "Monday" || day === "Friday") instead of if(day === "Monday" || "Friday"), else it'll always return on the first iteration.

PSS: As @adam mentioned, creating such a hashmap, e.g. from an array or unsanitized user input, might lead to a vulnerability called Prototype Pollution. I found a few useful resources on the topic I'll link below:

Collapse
 
adam_cyclones profile image
Adam Crockett 🌀

I had this conversation recently and something I had not considered is that due to the nature of proto and prototype based inheritance it is possible to pollute objects with malicious getters and so on given that untrusted code was not sufficiently sanitised, this makes objects a risk in that very unlikely scenario, switch wins due to its statement not being a part of the program itself.

Collapse
 
tqbit profile image
tq-bit

I find this quite important, especially since creating a hashmap from an array requires you to create keys manually. I'll add it to my comment

Collapse
 
j471n profile image
Jatin Sharma

I was gonna say that too.

+1

Collapse
 
zoreankit profile image
Ankit Zore

I find this elegant

Collapse
 
3monmon profile image
Simon • Edited

You can remove some of your console.log by writing something like this :

switch(day) {
 case 'Monday':
 case 'Friday':
  console.log('4am wake-up')
  break
 case 'Tuesday':
 case 'Wednesday':
 case 'Thursday':
  console.log('6am wake-up')
  break
 case 'Saturday':
 case 'Sunday':
  console.log('Sleep in')
  break
 default:
  console.log('No matches.')

}

Enter fullscreen mode Exit fullscreen mode
Collapse
 
grantdotdev profile image
Grant Riordan • Edited

Hey , 👋

Didn't know if you are aware but you can use logical operators in a switch case like so.

const savings = 100;
switch(true)
    case x > 500:
        return '50% Plus savings';
    case x < 500 && x > 200:
        return 'More than 20% off';
    default: 
        return '10% or less';
Enter fullscreen mode Exit fullscreen mode
Collapse
 
jonrandy profile image
Jon Randy 🎖️

You CAN NOT use logical operators in the switch case statements

This isn't correct. You can use logical operators:

switch (true) {
  case a && b:
    // do something
    break;
  case a && !b:
    // do another thing
    break;
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
mmcshinsky profile image
Michael McShinsky • Edited

statement is also the definition of the action to execute after the matching case, which is also another location in which you can implement complex logic.