When to Ternary

While the ternary operator is incredibly useful for concise code, it should be used judiciously. In general practice, you will likely use standard if/else statements more often than ternaries.

The Golden Rule

Ternary operations are great for small, single-line conditionals.

When logic becomes complex, some developers attempt to get “clever” by nesting ternary operators. This leads to code that is technically functional but extremely difficult to read.

Bad Practice (Nested Ternaries)

const vehicleName = isTruck
  ? "truck"
  : isCar
    ? "car"
    : isScooter
      ? "scooter"
      : "vehicle";

While it fits on one statement block, parsing this visually requires unnecessary mental overhead.

Good Practice (Clear Control Flow)

Remember that code is written for humans, not machines. The nested ternary is much easier to understand when written as an if/else chain or a standalone function.

let vehicleName = "vehicle";

if (isTruck) {
  vehicleName = "truck";
} else if (isCar) {
  vehicleName = "car";
} else if (isScooter) {
  vehicleName = "scooter";
}

Alternatively, extracting it into a function allows you to use clean return statements:

function getVehicleName(isTruck, isCar, isScooter) {
  if (isTruck) return "truck";
  if (isCar) return "car";
  if (isScooter) return "scooter";
  
  return "vehicle";
}