The Ternary Operator, Used Well

The only three-part operator, its associativity, and when nesting helps versus hurts.

Syntaxcondition ? valueIfTrue : valueIfFalse

condition ? a : b is an expression, so it fits anywhere a value is expected: an argument, a return, a template literal, an object property.

It nests, and it is right-associative

A chained ternary reads like an if/else-if ladder when you format it that way:

const size =
  n < 10  ? 'small'
  : n < 100 ? 'medium'
  : 'large';

Because it associates right, each : pairs with the nearest preceding ?, which is exactly the ladder behaviour you want.

Where it shines

Inside JSX, template strings, and default computations, a ternary keeps you in expression-land where statements are not allowed.

Example

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

When to use it

  • Choose between two JSX elements inline based on authentication state in a React component.
  • Set a CSS variable value in a style attribute based on a dark-mode boolean without an if statement.
  • Build a concise role-based permission label by nesting ternary expressions for three roles.

More examples

Ternary as inline expression

Uses the ternary operator to select a redirect route based on authentication state.

Example · js
const isAuth = false;
const route = isAuth ? "/dashboard" : "/login";
console.log(route); // "/login"

Nested ternary for three states

Chains two ternaries to map three role values to their display labels without an if-else block.

Example · js
const role = "editor";
const label = role === "admin"
  ? "Administrator"
  : role === "editor"
    ? "Editor"
    : "Viewer";
console.log(label); // "Editor"

Ternary in template literal

Embeds a ternary inside a template literal to choose singular or plural wording for the item count.

Example · js
const items = 5;
const msg = `Cart: ${items} ${items === 1 ? "item" : "items"}`;
console.log(msg); // "Cart: 5 items"

Discussion

  • Be the first to comment on this lesson.
The Ternary Operator, Used Well — JavaScript | SoundsCode