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.
condition ? valueIfTrue : valueIfFalse
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
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 : emeansa ? 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 : cassigns the result;a + b ? c : dtestsa + b. When in doubt, use parentheses. - Prefer it for values, not actions.
cond ? doA() : doB()as a statement works, butif/elseis clearer when you aren't using the result. - Don't nest deeply. Beyond two levels, use
if, a lookup object orswitch. - 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
&&oriffor 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.