Can I include more than one condition in a case of a switch statement like this?

@DanCouper Good points. Readability is a key factor. Your example certainly seems to meet that requirement. I personally like the symmetry of the switch statement.

Huh, Googling around, it looks like some Javascript people are ok with switch (true) and others hate it. Most other languages seem to consider it an abomination, so I guess this is my C roots coming through.

switch (true) {
  case (cond 1):
    ...
  case (cond 2):
    ...
  case (cond 3):
}

vs

if (cond 1) {
  ...
} else if (cond 2) {
  ...
} else if (cond 3) {
  ...
}

Personally I find the misalignment less unsightly than fighting the purpose of a switch, but I suppose its a matter of convention in each language.

Imo it’s often useful because of how explicit it is + the fall through semantics. For example, I wrote a credit card validator recently that uses this, recursive with the string being gradually built up and checked, with the order regexes are ran being critical. It was much easier mentally to deal with a switch because it involved a lot of reordering of the 20-30 branches. It can be done with if/else, it’s just that the particular way switches work makes it a good fit in some cases.

I do wonder how much people using it this way comes from exposure to modern languages that have match expressions (eg the ones mentioned, or the functional languages match expressions come from), and wanting access to those semantics; switch (true) gives you a very primitive version of that. if/else is generally a blunt tool in comparison. As I said, if (hopefully when, as the proposal is backed with MS, Facebook & NPM developer time) pattern matching is added to JS, point becomes moot.

Possible caveat that I’m coming from a perspective where I have a function that takes a value, then that value is passed into the switch and each branch always returns a value; I think this is important in that it removes the break footgun. The semantics of switch aren’t great, particularly because cases are not scoped (for good reason), the whole switch being a block (vs if/else with individually scoped blocks).

Notice that you can´t compare variables in case statements, you have to do that in a “if” function.
Saludos desde Argentina sorry for my English.

1 Like

@elParco

It is great that you solved the challenge, but instead of posting your full working solution, it is best to stay focused on answering the original poster’s question(s) and help guide them with hints and suggestions to solve their own issues with the challenge.

We are trying to cut back on the number of spoiler solutions found on the forum and instead focus on helping other campers with their questions and definitely not posting full working solutions.

Thank you for understanding.

2 Likes

Hi @ilenia! This was my first answer in the forum. I already updated it. Sorry I will take care on not posting solutions next time :relaxed:

1 Like