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.

8 minute lesson

~~~

The conditional operator chooses one of two expressions and produces its value:

This is how it looks:

condition ? valueWhenTrue : valueWhenFalse

Only the selected branch is evaluated:

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

The condition uses JavaScript truthiness. If you need an exact boolean rule, write it explicitly rather than relying on a value such as 0 or an empty string accidentally choosing a branch.

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

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

Use if when the branches perform several statements or need names and comments. Nesting ternaries quickly hides the decision structure:

// 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 using a ternary only for side effects such as running ? stop() : run(). An if/else communicates an action more clearly.

Try it: rewrite one simple if/else assignment as a ternary, then find a multi-step ternary and rewrite it as if/else. Explain why each form fits its case.

Lesson completed