Published on

Using Switch Cases Fall Through Or Array Includes For Cleaner Code

Authors

Today I had to enhance some existing code. While doing this I came across a fairly large switch case which was a pain to read. One thing I noticed is that many of the returns in the cases where the same meaning I could group these together for better readability somehow. Using FizzBuzz as an example I had:

switch (num) {
  case 1:
    return '1'
  case 2:
    return '2'
  case 3:
    return 'Fizz'
  case 5:
    return 'Buzz'
  case 9:
    return 'Fizz'
  case 15:
    return 'FizzBuzz'
  case 30:
    return 'FizzBuzz'
}

There is clearly repetition in the above and it would be nice to collapse this some how. One option using if statements together Array.includes would be:

if ([3, 9].includes(num)) {
  return 'Fizz'
}

if (num === 5) {
  return 'Buzz'
}

if ([15, 30].includes(num)) {
  return 'FizzBuzz'
}

return num + ''

That is one option which collapses the different cases nicely. But if you want to stick to using a switch you could use fall through instead to do something like:

switch (num) {
  case 5:
    return 'Buzz'
  case 3:
  case 9:
    return 'Fizz'
  case 15:
  case 30:
    return 'FizzBuzz'
  default:
    return num + ''
}

This is obviously a contrived example and not how you would solve FizzBuzz but this gives a good feel for how fall through or array include can be used to collapse repeated conditions in a switch or if block.