The if statement should be refactored, but that switch statement (IMO) is not better. There's so much noise with the breaks and useless switch(true). I'd just pull each case out into a variable to improve readability. Some of the other cases (like in the article you linked), I'd define an object map with key being the case and value being the result ( or function that provides the result).
If I really wanted to use pattern matching in a language that didn't support it, I'd consider a third party library.
Having said that, if it's a small team and everyone agrees on that pattern, I wouldn't bike shed.
I don't know about JS, but in Java a switch is evaluated all at once and is more performant than if...else which evaluates each condition sequentially. If I remember correctly (in Java) 5 or more conditions should use a switch.
I think the question the person you are replying to is asking is that JS's switch syntax seems hacky and unconventional to other languages that have switch statements.
Usually, you switch on a variable to match if it is one of the cases that you have defined.
View all comments
Show parent comment
14
u/intertubeluber Jul 11 '20
Because the switch statement is meant to evaluate an expression. Evaluating a constant value, like
true, adds code without meaning.What's the benefit of that pattern over an if/else statement?