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

Ternary Operator

Sometimes using 3-5 lines of code to write an if/else block is overkill. The ternary operator makes it easy to write a conditional as a single expression.

const price = isMember ? "$2.00" : "$10.00";

I like to read it in English as:

If isMember is true, evaluate to $2.00, otherwise evaluate to $10.00.

The same logic using if/else would be:

let price;
if (isMember) {
  price = "$2.00";
} else {
  price = "$10.00";
}

Why Is It Called a “Ternary”?

Ternary's latin root means "3", and it's the only JavaScript operator that takes three operands.

  • A condition followed by a question mark (?)
  • An expression to execute if the condition is truthy followed by a colon (:)
  • The expression to execute if the condition is falsy.

Assignment

On line 6, create a variable called messageStatus and use a ternary operator to set the value of that variable to either:

  • "Processing": the number of retries is less than the limit
  • "Failed": the number of retries is greater than or equal to the limit

Use the ternary operator and a comparison operator to dynamically determine which string to set as the value of messageStatus to.