Conditional (ternary) operator
Picks one of two values by a condition — a short if...else.
Available since: ES1
Syntax
condition ? valueIfTrue : valueIfFalseExamples
Picking a value:
const age = 20;
console.log(age >= 18 ? 'adult' : 'minor');Output:
adultInside a template literal:
const count = 1;
console.log(`${count} ${count === 1 ? 'item' : 'items'}`);Output:
1 itemNotes
Good for choosing a value in one expression. Do not nest ternaries — for several options if...else or switch read better.
See also
- Logical AND (&&) — Logical AND: returns the first falsy value, or the last one.
- Nullish coalescing (??) — Returns the right-hand value if the left is null or undefined.
In the tutorial
- Conditions — Branching in JavaScript — if, else, else if, truthy and falsy values and the ternary operator.