Conditional assignment
Assigning a value based on one boolean or comparison.
JS Puzzles · Const
JavaScript’s conditional (ternary) operator selects one of two values from a condition. Chained ? expressions are grouped right-to-left, enabling compact multi-condition selection.
A conditional expression evaluates its condition and produces the value after ? when truthy or after : otherwise. When conditional operators are chained, they group from right to left, allowing an if/else-if/else-style value selection.
condition ? value1 : value2| Name | Type | Description |
|---|---|---|
condition | expression | Expression tested for truthiness. |
value1 | expression | Expression returned when condition is truthy. |
value2 | expression | Expression returned when condition is falsy. |
The selected value: value1 when the condition is truthy, otherwise value2.
?, the truthy result between ? and :, and the fallback result after :.if when the branches need to execute different statements.const score = 82;
const band = score >= 90 ? "A" : score >= 80 ? "B" : "C";
console.log(band); // BThe conditional operators associate from right to left, so this behaves like checking the first condition, then the second only if needed.
Assigning a value based on one boolean or comparison.
Selecting one of several labels or values from ordered conditions.
Returning a computed value directly from a function.
The conditional operator is right-associative. Therefore, a ? b : c ? d : e groups as a ? b : (c ? d : e), which supports an if/else-if/else-style chain.
Follow-up: What does right-associative mean here? It describes implicit grouping, not that every operand is evaluated immediately; the condition determines which result expression is selected.
The condition is evaluated first. If it is truthy, the expression after ? supplies the result; otherwise, the expression after : supplies it.
Follow-up: How would you make the grouping unambiguous? Add parentheses around the intended nested conditional, especially when the expression becomes difficult to read.
The syntax is condition ? value1 : value2. The operator has three operands: a condition and two alternative expressions.
Follow-up: When should it be replaced with if? Use if when different branches need to perform statements rather than simply select one value.
if...elseComparison operatorsLogical operatorsOperator precedence