DEV Community

Discussion on: Stop using switches the wrong way, use this instead

Collapse
 
thepeoplesbourgeois profile image
Josh • Edited

You can also use this approach to break more complex switch cases into object functions, allowing you to turn this

switch (fruit) {
  case 'banana':
    document.body.style.backgroundColor = 'yellow';
    ...
    break;
  case 'grape':
    document.body.style.backgroundColor = 'purple';
    document.body.style.color = 'white';
    ...
    break;
  ...
}
Enter fullscreen mode Exit fullscreen mode

into this

const fruitThemes = {
  set_banana() {
    document.body.style.backgroundColor = 'yellow';
    ...
  },
  set_grape() {
    document.body.style.backgroundColor = 'purple';
    document.body.style.color = 'white';
    ...
  },
  ...
}

fruitThemes[`set_${fruit}`]?.()
Enter fullscreen mode Exit fullscreen mode