3

This is a straight up question, but in a switch statement is it ok not to return a default state?

The switch statement is in a React Component and looks like this.

const App = (chosenTeam) => {
    const renderSection = (team) => {
        switch (team) {
          case 'LFC':
            return <Liverpool />;
          case 'MUFC':
            return <TerribleTeam />;
          case 'Chelsea':
            return <Blues />;
        }
    }

    return {renderSection(chosenTeam)}
}
peter flanagan
  • 9,195
  • 26
  • 73
  • 127

2 Answers2

5

No, it's optional refer to switch on MDN:

default Optional

A default clause; if provided, this clause is executed if the value of expression doesn't match any of the case clauses.

Regardless, you should use a dictionary object instead of switch:

const team = {
  LFC: <Liverpool />,
  MUFC: <TerribleTeam />,
  Chelsea: <Blues />
};

const App = chosenTeam => <>{team[chosenTeam]}</>;

The main aspect is that you are getting all functionalities of an object.


Note, rendering components inside the component body may cause performance tradeoffs (unless they memoize):

const App = chosenTeam => {
  //         v Executed on *every* render
  const renderSection = team => { ... };

  return <>...</>;
};
//        v Should be in the outer scope if you keeping the function
const renderSection = team => {
  switch (team) { ... }
};

const App = chosenTeam => {
  return <>...</>;
};
Community
  • 1
  • 1
Dennis Vash
  • 50,196
  • 9
  • 100
  • 118
1

If you know that the switched value will be in one of the stated cases, then no, the default case is unnecessary, because it'll never be reached.

But switch can be error-prone and unnecessarily verbose in many cases. You might consider using an object indexed by team name instead:

const teams = {
  LFC: () => (<Liverpool />),
  MUFC: () => (<TerribleTeam />),
  Chelsea: () => (<Blues />)
}
const App = (chosenTeam) => {
  return {teams[chosenTeam]()}
}
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320