Today I learned that some people writing javascript use `switch(true)` instead of writing if-statements and now I want to learn to write javascript even less than my cheery negative eleventy bajillion disposition.

@ben switches and selects are, but not switch of a `true` literal.

@cj I think people feel switch statements are a little bit more readable than if/else if you're doing the same test on multiple values. But it's not ideal.
I was going to propose to TC39 adding syntax to `switch` that improves things a bit, when I can find some time.

@Paul switch on a `true` literal is inverting the intended idea that switch syntax is meant to convey, which is why I don't like it.

@cj I agree with you there, I'm just saying I understand why people do it - there's a gap in the language so people end up abusing the features that do exist.

@Paul @cj What’s the gap in the language? Why isn’t if-statements more fitting?

@bjonte in my opinion the gap is being able to run the same test on multiple different arguments without repeating the same code, and branch depending on the outcome. In the end switch(true) isn't really any different than using if statements, but I think developers take that route because it feels more natural that a switch-like syntax would be used for that scenario, if it were available. But it's not so they choose the next closest thing.


So basically, JavaScript is in need of a typecase equivalent from Common Lisp.

(typecase error
(type-error ..)
(custom-error ...)
(otherwise ...))

I can understand the need; in my experience, I use typecase (usually etypecase, which doesn't have an "otherwise" clause and instead fails by default) much more than any of the normal switch/case equivalents...


@temporal @cj Yeah something like that, but maybe even broader so it's not just restricted to type checking - the other key example is matching a url string against a series of regular expressions.

Sign in to participate in the conversation
Mastodon for Tech Folks

This Mastodon instance is for people interested in technology. Discussions aren't limited to technology, because tech folks shouldn't be limited to technology either!