Search code examples
javascriptif-statementconditional-operator

Is there a better way to write this nested if else statement?


if (restroom) {
  if (fleet) {
    secondIconM9;
  } else {
    secondIcon;
  }
} else {
  if (fleet) {
    firstIconM9;
  } else {
    fistIcon;
  }
}

This is the code that I have written. It works and I can refactor it into a ternary but I have a feeling that this is unnecessarily descriptive. Is there a way to better write this nested if-else condition.


Solution

  • This keeps things legible and reduces the if/else nesting. That is of course if this code is in a function that returns the icon. Otherwise you'll need the else statement.

    if (restroom) {
      return (fleet) ? secondIconM9 : secondIcon;
    }
    return (fleet) ? firstIconM9 : firstIcon;