Conditions
The ternary operator ? :
Picking one of two values on one line.
Why it exists
Very often a condition is needed not to do something but to pick a value: what text to show on a button, what word to put after a number, what class to give an element. With if...else you have to create a variable and assign it in two branches. The ternary operator is a value itself — you can return it, assign it or drop it into a template string directly.
Where it's used
- Interface text:
isLoggedIn ? "Log out" : "Log in". - Plurals:
count === 1 ? "item" : "items". - Markup in React:
{isLoading ? <Spinner /> : <List />}. - A value by condition:
const fee = total > 1000 ? 0 : 300.
Syntax
condition ? valueIfYes : valueIfNoExamples
const age = 20;
age >= 18 ? "adult" : "child"; // → "adult"const count = 1;
`${count} ${count === 1 ? "file" : "files"}`; // → "1 file"const total = 1500;
const fee = total > 1000 ? 0 : 300;
fee; // → 0const n = 0;
n > 0 ? "plus" : n < 0 ? "minus" : "zero"; // → "zero"Results after // → aren't just written down — an automatic check runs and verifies them before every site update.
Why it works this way
The condition is evaluated first. If it's true (more precisely, "truthy"), the expression after ? is evaluated and becomes the result. Otherwise it's the expression after :. The other branch is not evaluated at all.
The ternary operator is an expression, not a statement: it has a value. So it can go anywhere a value is expected: after return, on the right of =, inside ${ }, as a function argument. An if can't go there.
Ternaries can be nested: a ? x : b ? y : z. It reads as an "else if" chain, but even two levels get heavy.
Traps
How it differs from…
if...elseif...else runs one of two branches of code and can do anything in them. A ternary is an expression that picks one of two values.
- Logical operators
!,&&,|| a || banda ?? bare short forms for the special case "takea, and if there's none,b".
When to pick something else
Don't use a ternary if a branch needs several actions, if there are more than three options, or if the line doesn't fit on the screen. In those cases if...else or early return read better.