Ternary Operator

Sometimes writing out a full if/else block spanning 5 lines of code is overkill for a simple true/false check. The ternary operator provides a concise way to write a conditional as a single expression.

Syntax

The ternary operator is the only JavaScript operator that takes three operands:

  1. A condition followed by a question mark (?)
  2. An expression to execute if the condition is truthy, followed by a colon (:)
  3. The expression to execute if the condition is falsy.
const price = isMember ? "$2.00" : "$10.00";

You can read this statement in plain English as: “If isMember is true, evaluate to $2.00, otherwise evaluate to $10.00.”

The exact same logic written using standard if/else would look like this:

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

Practical Example

Ternaries are often used to conditionally assign a string or state variable based on a limit or threshold.

const retryLimit = 10;
const numRetries = 9;

// If numRetries is less than the limit, status is "Processing", else it's "Failed"
const messageStatus = numRetries < retryLimit ? "Processing" : "Failed";

console.log(messageStatus); // "Processing"