Skip to content
Tutorials Center
My learning

Topics

JavaScript Reference ยท Operators

The ?: operator

Reference for the JavaScript conditional (ternary) operator ?: with syntax, chaining, use inside template literals and when an if statement reads better.

The conditional operator, usually called the ternary operator, is JavaScript's only operator with three operands. It evaluates a condition and then evaluates and returns one of two expressions. Because it is an expression, you can use it where a statement isn't allowed: inside a template literal, an argument list, a return value or an object literal.

JavaScript
condition ? valueIfTrue : valueIfFalse

Try it

JS Choosing a value

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS Only one branch runs

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Syntax

JavaScript
test ? exprIfTruthy : exprIfFalsy
Part Description
test Any expression. It is converted to a boolean: truthy picks the first branch, falsy picks the second.
exprIfTruthy Evaluated only when test is truthy.
exprIfFalsy Evaluated only when test is falsy.

Return value: the value of whichever branch was evaluated.

Exceptions: none of its own. Errors thrown inside the evaluated branch (or the test) propagate; the other branch is never evaluated.

Usage notes

  • Right-associative: a ? b : c ? d : e means a ? b : (c ? d : e), so chains read as an if / else if / else list. Keep them short and format one case per line.
  • Low precedence: only the comma and assignment-like operators bind looser. x = a ? b : c assigns the result; a + b ? c : d tests a + b. When in doubt, use parentheses.
  • Prefer it for values, not actions. cond ? doA() : doB() as a statement works, but if / else is clearer when you aren't using the result.
  • Don't nest deeply. Beyond two levels, use if, a lookup object or switch.
  • Mixing with ?? and ||: value ?? (flag ? a : b) needs parentheses to make your intent clear.
  • Both branches are required. There is no ternary without an else. Use && or if for a single branch.
  • Types: the branches can have different types, but code that gets a number in one case and a string in another is harder to use.

Browser support

Supported in every browser and runtime.