The Ternary Operator

A compact one-line if...else expression.

Syntaxcondition ? valueIfTrue : valueIfFalse

The ternary operator is a short way to choose between two values based on a condition. It is the only operator that takes three parts.

How it reads

condition ? valueIfTrue : valueIfFalse

It is an expression, so it produces a value you can store or log.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Render different button labels inline based on whether the user is following an account.
  • Assign a CSS class name based on whether a score passes or fails a threshold.
  • Choose between singular and plural wording in a notification based on an item count.

More examples

Inline conditional label

Selects between two strings inline using a ternary, ideal for rendering button text.

Example · js
const isFollowing = true;
const label = isFollowing ? "Unfollow" : "Follow";
console.log(label); // "Unfollow"

Assign class based on score

Uses the ternary to assign a CSS class name depending on whether a score meets the pass threshold.

Example · js
const score = 72;
const cssClass = score >= 60 ? "pass" : "fail";
console.log(cssClass); // "pass"

Plural vs singular wording

Embeds a ternary inside a template literal to choose between singular and plural wording.

Example · js
const count = 3;
const msg = `You have ${count} new ${count === 1 ? "message" : "messages"}.`;
console.log(msg); // "You have 3 new messages."

Discussion

  • Be the first to comment on this lesson.