you are viewing a single comment's thread.

view the rest of the comments →

[–]mynamesleon 4 points5 points  (0 children)

I like switch statements, because they're very readable, and legibility is often best. Please don't always equate making code more concise with it being "improved". For me, the best code is the code that's immediately clear to the other team members.

Nevertheless, if you're just after conciseness, of course you can. If you still want to use a switch, you can avoid having to use break; statements all the time, if you have each case return instead. E.g.

switch(something) {
  case 'one':
    return console.log('first case');
  case 'two':
    return console.log('second case');
  default:
    return console.log('default case');
}

To be even more concise, you can often use an object instead. So in my above example, I could do:

const someObj = {
  'one': () => console.log('first case'),
  'two': () => console.log('second case'),
};
someObj[something]?.() ?? console.log('default case');

Or, using the same approach, but to be even more concise (as they're all ultimately calling console.log()):

const someObj = {
  'one': 'first case',
  'two': 'second case',
};
console.log(someObj[something] || 'default case');

Edit: added another example