We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

When to Ternary

You will probably use if/else statements more often than ternaries. Ternary operations are great for small, single-line conditionals. I've seen developers in the professional world get... clever... with ternaries and it can lead to nested monstrosities like this:

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

I mean it works, and it's all on one line, but it's much harder to understand IMO. I'd prefer to see this:

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

or maybe a function (we'll cover functions soon):

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

Remember: Code is written for humans not machines.