DEV Community

Discussion on: A New Coding Style for Switch Statements in JavaScript/TypeScript

Collapse
 
wheelmaker24 profile image
Nikolaus Rademacher

ATM I prefer not writing switch statements and instead use conditional return statements like

const myFunction = () => {
  // ...
  return (
    (body.type === 'isBasic' && doBasicStuff()) ||
    (body.type === 'isCustom' && doCustomStuff()) ||
    new Error()
  );
};

Although this makes most sense when moving the conditions to distinct constants first, like:

const myFunction = () => {
  // ...
  const isBasic = body.type === 'isBasic';
  const isCustom = body.type === 'isCustom';
  return (
    (isBasic && doBasicStuff()) ||
    (isCustom && doCustomStuff()) ||
    new Error()
  );
};

Of course this depends on the use case. When having the necessity for more complex conditionals it might make sense to move them to distinct variables anyways and that's when this pattern shines...

Collapse
 
nebrius profile image
Bryan Hughes • Edited

This is a good one too. In the case of TypeScript, we do loose a bit of type checking (you can leave the default case off if the possible values are an enum IIRC), but this is good too.

I've really grown fond of using this approach in React specifically, since we can't have normal conditionals inside of JSX:

<div>
  {body.type === 'isBasic' && <BasicComponent />}
  {body.type === 'isCustom ' && <CustomComponent />}
</div>