Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Switch statements indicate "it's one of these things", whereas in the series of ifs any of them could be true. Using a switch statement tells the reader that you expect one of these things to happen [0]. Using a series of ifs tells the reader that these things might or might not happen depending, and they're going to have to read each statement to work out which.

Your last version doesn't tell the reader what your intention is at all, and they need to work out what you're trying to do here. It's a lot less readable. Unless you're desperate for those bytes, it'd be better to use the switch statement for this case.

[0]: This gets a little weird in languages like JS where switch statements fall through to the next one if you don't break or return, but generally it still holds true.



That's not how switches work: a switch can (and will) trigger lots of cases if you don't either `break` (highly unintuitive to new programmers, who like you believe switch is "do one of these") or `return`, either of which cuts cuts the switch short.


I don't think this line of reasoning makes sense, since as you acknowledge, JS switch has fallthrough. I would not immediately assume that the coder's intent was for only one branch to execute if I came across a 'switch' in some JS code.


Adding 'else's to the above code would make it superior to switch by these metrics (e.g. no fallthrough).


You should not use switch in JavaScript, because it is a language where switch requires break, which means it's 100% going to bite you in the ass unless you have a linter that checks for the break. It's not worth it for such a simple case.


With if you can also indicate "it's one of these things" by throwing an error at the end:

    if (cellA > cellB) return 1;
    if (cellA < cellB) return -1;
    if (cellA === cellB) return 0;
    throw new Error();


Let me tell you about if..else!




Consider applying for YC's Summer 2026 batch! Applications are open till May 4

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: