JavaScript / PHP · Beginner
Ternary operator vs if / else: a readability rule that holds up
Choose between a conditional expression and an if / else statement using result shape, side effects, nesting, and debugging—not character count.
The ternary operator is a conditional expression: it produces a value. An if / else is a conditional statement: it controls which statements run. That distinction gives a better rule than “use a ternary when it is short.”
const label = isOnline ? 'Online' : 'Offline';
Read it as: “label is Online if isOnline is true; otherwise it is Offline.” One condition selects one of two values, so the expression fits naturally.
The equivalent if / else
The same decision can be written as a statement:
let label;
if (isOnline) {
label = 'Online';
} else {
label = 'Offline';
}
Neither version is more correct. The ternary emphasises that one variable receives one of two values. The statement gives each branch room to grow.
Use a ternary for symmetric values
A strong ternary has a visible shape:
const fee = isMember ? 0 : 12;
const icon = expanded ? 'chevron-up' : 'chevron-down';
const greeting = name ? `Hello, ${name}` : 'Hello';
The middle and final operands have the same conceptual role: both are possible values for the same result.
Ternaries also work well inside function calls or returned data when the result remains simple:
return {
status: error ? 'failed' : 'complete',
retryable: error ? error.isTemporary : false,
};
Use if / else when branches do work
Once each branch performs a sequence, a statement makes order and side effects clearer:
if (payment.succeeded) {
markInvoicePaid(invoice);
sendReceipt(invoice);
metrics.increment('payments.complete');
} else {
recordFailure(payment.error);
scheduleRetry(invoice);
}
Compressing these calls into comma expressions or immediately invoked functions would produce an expression, but it would hide the procedural nature of the code.
Use the construct that represents what is happening. Selecting data is expression-shaped; performing workflows is statement-shaped.
Avoid nested ternary puzzles
A nested ternary can represent several outcomes:
const label = score >= 90
? 'excellent'
: score >= 70
? 'good'
: score >= 50
? 'pass'
: 'not yet';
Formatting helps, but readers must still pair each ? with the correct :. An ordered statement makes priority explicit:
function scoreLabel(score) {
if (score >= 90) return 'excellent';
if (score >= 70) return 'good';
if (score >= 50) return 'pass';
return 'not yet';
}
A lookup can be even clearer for exact keys. The ternary is strongest when it remains binary.
Do not use truthiness when zero is valid
The condition has the same coercion rules as an if statement:
const quantityLabel = quantity
? `${quantity} available`
: 'Unknown quantity';
This reports zero as unknown. Compare the missing value you mean:
const quantityLabel = quantity == null
? 'Unknown quantity'
: `${quantity} available`;
Changing syntax does not change the need for a precise condition.
PHP uses the same three-part shape
PHP’s full ternary operator has the same order:
$label = $isOnline ? 'Online' : 'Offline';
Modern PHP code should be cautious with chained unparenthesised ternaries. Their associativity changed across language versions, and unparenthesised chaining is not supported in current PHP. Prefer a match expression, a clear if chain, or explicit parentheses for a genuinely nested binary decision.
PHP also has a shorthand form:
$displayName = $nickname ?: 'Anonymous';
It uses $nickname itself when truthy and the fallback otherwise. That means the string '0' and numeric zero also trigger the fallback. Use null coalescing when only missing/null should fall back:
$displayName = $nickname ?? 'Anonymous';
Debugging is a legitimate design signal
An if / else gives you obvious lines for breakpoints, logging, or inspecting intermediate values:
let price;
if (coupon.isValidFor(cart)) {
const discount = coupon.calculate(cart);
price = cart.total - discount;
} else {
price = cart.total;
}
If understanding a branch needs an intermediate name, give it one. Saving lines is not valuable when it removes the name that explains the calculation.
The practical rule
Use a ternary when all four statements are true:
- There are exactly two outcomes.
- Both outcomes are simple values or expressions.
- The condition is easy to understand where it appears.
- The expression reads naturally when spoken as “this if condition, otherwise that.”
Use if / else when a branch performs work, needs multiple lines, benefits from intermediate names, requires commentary, or may gain another outcome. Choose for the shape of the decision, not the number of characters.
The JavaScript examples were run with Node.js 22.14.0 and the PHP examples with PHP 8.4.4. Each paired form was checked for the same result.