Conditional (ternary) operator (?:)

Chooses between two expressions based on a condition.

Since ES1 Spec ↗

Syntax

condition ? exprIfTruthy : exprIfFalsy

Returns

any — The value of `exprIfTruthy` when `condition` is truthy, otherwise `exprIfFalsy`.

Examples

const age = 20;
const status = age >= 18 ? "adult" : "minor";
console.log(status);
Output
adult
const n = 0;
console.log(n === 0 ? "zero" : "nonzero");
Output
zero
const score = 75;
const grade = score >= 90 ? "A" : score >= 80 ? "B" : "C";
console.log(grade);
Output
C

Notes

- The only JavaScript operator with three operands. - It is an expression, so it can be used inline where statements like `if` cannot. - Chaining is possible but deep nesting hurts readability.

Browser & runtime support

EnvironmentSince version
chrome 1.0
firefox 1.0
safari 1.0
edge 12
node 0.10

See also