condition
The question that is converted to true or false.
The ternary operator chooses between two expressions. It is perfect for small value choices and terrible for hidden complex logic.
const label = isReady ? "Open editor" : "Complete setup"; button.textContent = label;
Operators & Expressions
The conditional operator is the only JavaScript operator with three operands: condition ? expressionIfTrue : expressionIfFalse.
It is an expression, so it produces a value. That makes it useful inside assignments, template strings and rendering logic.
The danger is nesting. If a ternary becomes a mini-program, use if/else or a named function instead. Readability wins.
The question that is converted to true or false.
The expression returned when the condition is truthy.
The expression returned when the condition is falsy.
The whole ternary returns one value.
Examples
const hasCompletedSetup = true; const buttonLabel = hasCompletedSetup ? "Open dashboard" : "Complete setup"; button.textContent = buttonLabel;
const label = score > 90 ? "Excellent" : score > 70 ? "Good" : score > 50 ? "Okay" : "Try again"; // Legal, but hard to scan quickly.
Rules that matter
JavaScript operators are compact, but compact is not always clear. Convert values before comparing or calculating, use strict checks by default and add parentheses when a future reader would otherwise need to remember a precedence table.
A ternary should answer one simple question.
Long branches belong in variables or functions.
Use if/else or a lookup object when there are many cases.
const canSubmit = ... makes the ternary easier to read.
A ternary should choose a value, not perform hidden work.
Line breaks can make a ternary readable when the pieces are still small.
Production thinking
Ternaries are excellent when they reduce noise. They are harmful when they compress too much logic into one line.
Ternaries often choose labels and messages. Keep that logic clear so UI text remains predictable.
Production code should avoid clever nested ternaries in business rules. They are hard to review and easy to break.
Conditional labels, headings or metadata should be selected with clear logic so rendered text stays correct.
Live code lab
The preview runs inside an isolated iframe. The JavaScript is placed inside the HTML editor for now, so every example stays together and remains easy to understand.
Mini assignment
Practice assignment
Try it yourself
Self-check
Say the answer in plain language. If you can explain the operator behavior, you can debug the expression.