JavaScript switch vs if - What's the difference?

344    Asked by Jiten in Java , Asked on Oct 6, 2022

I am developing a game in JavaScript where you start with a user input, stored in the variable "controller". The options for the user consists of starting to start the game or about to learn about the game. I was going to use the following code

if(controller === "start"){
    // Game code sitting here
}
else if(controller === "about"){
    // All about the Game
}
else{
    // Tells the user again to type start to start or about to learn about the game
}

when I realised that I should maybe use switch cases instead...

So, my question is when to use switch cases instead of if statements and which I should use in this case. I would also like to know if you think I should store my game code in a function and call it if the controller is equal to "start" or just have it sitting inside the if statement/switch case as it is atm?

Answered by Jiten Testing

JavaScript switch vs if


semantics.

Personally, in a situation like this, I make a judgement call as to which one will be easier to understand.

What influences the ease of understanding, again, in my opinion, is maybe a combination of several factors:

Collectively exhaustive - Is there a specific way to handle each legal value? If so, a switch may be in order.

Dependency / mutual exclusive - Do any conditions depend on each other? If so, an if statement may be more flexible.

More than 2 cases - switch/case has some cognitive overhead for me, so I would be annoyed to see a switch/case for true/false. Possibly because if (x) { } else { } is leaner.

How similar are the actions? Do they fall in the same domain? If one case sets or returns a variable, while another case executes a function that mutates some state and another case prints / outputs a piece of information, I would not make that a case because the cases are not related at all. If they all, however, switch on a menu selection and execute a different function as the next step, that is a good switch because all cases choose a "next step".

The first two, collectively exhaustive and mutually exclusive, come to me by thinking about a physical switch. Let's say I have a switch that can be in 5 states. To really be a switch, it can only be in one state at any given time. It can never not have a state and it cannot co-exist with another state. In software, this is like saying that for any input, at least one of the case statements must match (including the default)..

Again, this is my personal preference. I do not know if there is any official guideline on this.



Your Answer

Interviews

Parent Categories