? :
The conditional (ternary) operator returns one of two values depending on a condition, in one short expression.
- Returns
- The value
exprIfTruewhen the condition is truthy, otherwise the valueexprIfFalse. Only the chosen expression is evaluated.
Example
#const points = 85
const isPremium = false
const result = points >= 50 ? 'Passed' : 'Needs improvement'
console.log(result)
console.log(`Account: ${isPremium ? 'Premium' : 'Free'}`)Definition and usage
#The conditional operator, also called the ternary operator, has three parts: a condition, a value for when it’s true, and a value for when it’s false. The form condition ? a : b returns a when the condition is truthy, and otherwise b.
Unlike if...else, this is an expression, not a statement. So you can drop it directly into an assignment, a function argument, a template literal, or React JSX, e.g. const label = points >= 50 ? "Passed" : "Needs improvement".
You can chain the operators to pick one of several values, but past two or three levels the code loses readability. At that point, if...else, switch, or a separate function work better.
Syntax
#condition ? exprIfTrue : exprIfFalseMore examples
#const medal = (place) =>
place === 1 ? 'gold'
: place === 2 ? 'silver'
: place === 3 ? 'bronze'
: 'none'
console.log(medal(1))
console.log(medal(3))
console.log(medal(7))function reward() {
console.log('Reward granted')
return 50
}
const finished = false
const bonus = finished ? reward() : 0
console.log(bonus)reward() was never called, because the condition was false. The operator only evaluates one of its two branches.
Browser support
#Widely available
Works in all modern browsers, phones included. You can use it without worry.
- Chrome
- Edge
- Firefox
- Safari
Good practices
#- Use the operator to choose a value, not to trigger an action. The form
isValid ? save() : showError()reads more clearly asif...else. - When it’s just about a default value,
??and||are shorter:name ?? "Guest". - Format nested conditions on separate lines, starting each one with
?or:. It’s then easier to see which value belongs to which condition.
Related entries
#- if...elseRuns a block of code only when the condition is true, and otherwise an optional else block.
- &&, ||, !The logical operators AND (&&), OR (||), and NOT (!). They combine conditions, and && and || return one of their sides.
- ??The ?? (nullish coalescing) operator returns the right side only when the left side is null or undefined. Ideal for default values.
- switchCompares a value against a list of case labels and runs the code from the first match.
- Template literalsText templates in backticks: insert values with ${} and span multiple lines.
Spotted a mistake or missing an example? Write to us.