Rethinking JavaScript: Eliminate the switch statement for better code
Joel Thoms

switch is not ‘side-effecty’. It has 0 side effects apart from whatever you cause. Agreed that it won’t compose well, though. The main issue with switch is that it’s a block rather than an expression.

The main annoyances about switch being a block, other than not being composable, are that

  • the cases are not blocks
  • default is not enforced

Since cases are not blocks, any names you declare within them are declared in all cases. Your solution that uses functions, as well as Ramda’s cond() solve this issue by using functions for cases. Now each case has its own scope, and there’s no name-management hell.

With ES6, we can solve this issue by using blocks.

switch (foo) {
case 'some': { // <-- another pair of curlies here
const some = 1
return foo + some
case 'thing': {
const some = 'again'
return foo + ' ' + some
default: {
return foo

You can’t really enforce the default, but there are linter rules that can help you there.

Obviously, even with all these helpful mods, switch is still a block, so you can’t return it, pass it around, or compose. You could wrap it in an IIFE, but, my god, the syntax noise!

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.