When should I use an if statement, a ternary operator, or the && operator?

Question

When should I use an if statement, a ternary operator, or the && operator?

Answer

We should decide to use either an if statement, ternary operator, or the && operator based on what is most concise while still maintaining readability.

Tips to help decide on which conditional statement or operator to use:

  • the && and ternary operators are more concise, choose either of these when possible
  • choose the && over a ternary when you want an action to occur (or not) based on a single condition
  • choose an if/else/else if statement when you need to extrapolate logic to make it easier to read and understand
9 Likes