JavaScript Conditional Operator: Choose a Value
Quick answer
The conditional operator condition ? yes : no is an expression that produces one of two values. It is useful for a small choice inside an assignment or return.
How it works
The condition is converted to truthiness. Exactly one of the two result expressions is evaluated. Unlike an if statement, the operator itself produces a value. The operator is right-associative, but deeply nested choices are often clearer as statements.
const score = 72;const label = score >= 60 ? "pass" : "retry";console.log(label);Expected output in Node.js:
passOnly the first result expression is evaluated.
let visits = 0;const price = false ? ++visits : 8;console.log(price, visits);Expected output in Node.js:
8 0The unselected branch never increments visits.
Common mistakes
Do not mistake ? : for optional chaining ?., or use nested conditional expressions to hide complicated business rules.
Practice
Return a pass or retry label using an inclusive score threshold.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
JavaScript Conditional Operator: Choose a Value — Knowledge Check
Apply the taught concept and reason about the result.
What is 6 > 4 ? "A" : "B"?
How many result branches does a conditional expression evaluate?
After let n=0; false ? ++n : 7; what is n?
Which structure is a value-producing expression?
When should a complex nested conditional be rewritten?