Decisions and repetition

JavaScript Ternary Operator

Learn how the JavaScript ternary operator gives you a short way to write a conditional with three operands, choosing one of two expressions to run.

The ternary operator picks one of two expressions and returns its value:

condition ? valueWhenTrue : valueWhenFalse

Only the selected branch runs:

const label = isSaving ? 'Saving…' : 'Save'

The condition follows normal truthiness rules. When 0 or '' are valid data, write an explicit comparison instead of relying on truthiness.

Use a ternary when the result belongs in an assignment, return, template, or argument:

function accessLabel(isAdmin) {
  return isAdmin ? 'Administrator' : 'Member'
}

Use if/else when each branch needs several statements or comments.

Nested ternaries get hard to read fast:

// Hard to scan
const fee = isMember ? isStudent ? 5 : 10 : 20

// Easier to extend and debug
let fee = 20
if (isMember) {
  fee = isStudent ? 5 : 10
}

Avoid ternaries whose only job is side effects like running ? stop() : run(). An if/else communicates action more clearly.

Parentheses help when the ternary sits inside a larger expression:

const message = (isLoggedIn ? 'Welcome back' : 'Sign in') + ', Flavio'

Without grouping, operator precedence can attach the ternary to the wrong neighbor.

Ternaries shine in JSX and template literals where an if block would break the expression grammar. In plain scripts, an if/else statement is often easier to step through in a debugger.

Another readable pattern is picking between two function references:

const handler = isEditing ? saveDraft : startEdit
handler()

The ternary returns a function value. You call it on the next line. Both branches must be callable if you use this pattern.

In React and other JSX codebases, ternaries are everywhere because JSX expressions cannot contain statements. The same rule applies inside template literals and object literals.

When a ternary grows wider than the screen, that is a signal to rewrite it as if/else or extract a helper function with a name that states the decision.

Rewrite one simple assignment from if/else to a ternary, then rewrite a nested ternary back to if/else. Compare readability and pick the form that matches the complexity.

Lesson completed