Stuart Clove

How to write a functional switch statement in Javascript

November 06, 2019

Here is a neat way to clean up your code by changing a classic switch statement in Javascript into a functional version.

Non-functional (BOO!)

let value = '';

switch (thing) {
  case 'ONE':
    value = 'One is what I wanted.';
    break;
  case 'TWO':
    value = 'Two is what I wanted.';
    break;
  case 'THREE':
    value = 'Three is what I wanted.';
    break;
  default:
    value = "That'll do pig.";
}

Functional (YAY!)

const value = (thing => {
  switch (thing) {
    case 'ONE':
      return 'One is what I wanted.';
    case 'TWO':
      return 'Two is what I wanted.';
    case 'THREE':
      return 'Three is what I wanted.';
    default:
      return "That'll do pig.";
  }
})(thing);

I’ve found that writing small things like this in a functional way makes my code a lot easier to test and less prone to errors.


Stuart Clove

Hi I'm Stuart Clove. I like to build things that help people. When I'm not focused on that, I'm usually playing guitar, with my family and friends, learning more about fitness, or petting my pups.