? :

The conditional (ternary) operator returns one of two values depending on a condition, in one short expression.

Returns
The value exprIfTrue when the condition is truthy, otherwise the value exprIfFalse. Only the chosen expression is evaluated.
On this page

Example

#
JavaScript
const points = 85
const isPremium = false

const result = points >= 50 ? 'Passed' : 'Needs improvement'
console.log(result)
console.log(`Account: ${isPremium ? 'Premium' : 'Free'}`)
Console
Passed
Account: 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

#
Syntax
condition ? exprIfTrue : exprIfFalse

More examples

#
A chain of conditions
JavaScript
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))
Console
gold
bronze
none
Only the chosen branch is evaluated
JavaScript
function reward() {
  console.log('Reward granted')
  return 50
}

const finished = false
const bonus = finished ? reward() : 0

console.log(bonus)
Console
0

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 as if...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

#

Spotted a mistake or missing an example? Write to us.