When programming, you often encounter simple conditional branches like 'if A, assign this value; otherwise, assign that value.' If you write all of these using if-else statements, the number of lines of code can grow, and the essential logic can become buried.
This is where the 'ternary operator' comes in.
When used properly, the ternary operator can dramatically clean up your code and improve readability. However, if used incorrectly, it can become synonymous with 'unreadable code.' In this article, I will explain the syntax in various languages and the criteria for 'choosing between ternary operators and if statements' that are useful in the field, from a professional perspective.
1. Basic Structure and Operating Principle of the Ternary Operator
The reason it is called 'ternary' is that it constructs a single expression using three elements (terms): the 'conditional expression,' the 'value if true,' and the 'value if false.'
The standard syntax adopted by many languages is as follows:
Conditional expression ? Value if true : Value if false
In the world of programming, there is a rule where the name of an operator changes depending on the number of values (terms) it handles.
Unary operator: Handles one value (e.g., ++ in i++, or - in -5 representing a negative number)
Binary operator: Calculates two values (e.g., + in 1 + 1, or > in a > b)
Ternary operator: It is called this because it handles three elements—'condition,' 'value if true,' and 'value if false'—as a set.
The standard syntax adopted by many languages is as follows:
Conditional expression ? Value if true : Value if false
Flow of operationFirst, the 'conditional expression' is evaluated (true or false).
If the condition is true, the value after ? is returned.
If the condition is false, the value after : is returned.
Comparison of code length with if statements (e.g., JavaScript)
In the case of an if statement
let statusLabel; // 後で値を書き換えるため、再代入可能な let が必要 if (isLoggedIn) statusLabel = "Online"; else statusLabel = "Offline";
In the case of a ternary operator
const statusLabel = isLoggedIn ? "Online" : "Offline";
The fact that it can be completed in just one line and can also be defined as a const (constant) is extremely powerful.
[Important] The ternary operator is an 'expression', while an if statement is a 'statement'This is the most important point that beginners should grasp to step up to an intermediate level.
if statement (Statement): An 'instruction' that controls the flow of processing. It does not hold a 'value' itself.
Ternary operator (Expression): Always returns a 'value' as the result of being evaluated.
Because the ternary operator acts as a 'value' itself, the following types of descriptions become possible.
Can be assigned at the same time as variable initialization When declaring a const (a constant that cannot be reassigned) in languages like JavaScript, an if statement requires assignment later, but with a ternary operator, the value can be determined at the same time as the declaration.
Can be written directly in function arguments You can switch the contents of printf or console.log on the fly depending on the condition.
2. [By Language] Ternary Operator Syntax Reference
The basics of the ternary operator are the same, but the syntax and whether it even exists vary by language.
JavaScript / TypeScript / Java / C# / PHPThese adopt the most standard ? : format.
Usage example (JavaScript)
// UIの表示切り替えなどで多用されます const statusLabel = isActive ? "オンライン" : "オフライン";
Unlike other languages, Python uses a unique syntax that is closer to English word order.
Syntax: true_value if condition else false_value
message = "合格" if score >= 60 else "不合格"
While intuitive and easy to read, you might feel a bit confused if you are used to other languages.
RubyRuby can also use ? :, but it has a feature where the 'if statement itself returns a value'.
Ternary operator format (smartly in one line)
result = is_success ? "完了" : "失敗"
if expression format(also common in Ruby)
result = if is_success
"完了"
else
"失敗"
endIt might be surprising, but the Go language does not have a ternary operator. Rust also lacks a symbol for a so-called ternary operator, but since if can return a value as an 'expression', that is used instead.
Alternative example in Rust
let theme = if is_dark_mode "Dark" else "Light" ;
Even without a dedicated symbol (? :) for the ternary operator, it is designed to be written smartly.
3. Which is correct? Criteria for choosing between ternary operators and if statements
You might think, 'Shouldn't I just write everything with ternary operators?', but that is not the case. What is important is 'whether the person reading the code later can understand it instantly'.
Scenes where you should use ternary operatorsSimple value assignment: When you just want to change the value put into a variable depending on a condition.
Variable initialization: When you want to determine a value at the same time as declaration, such as for a variable you want to specify as const.
Log output or function arguments: When you want to change a value supplementarily, like console.log("Result: " + (success ? "OK" : "NG"));.
When the code is completed in one line and the intent is conveyed at a glance.
When the process spans multiple lines (two or more lines): When you call multiple functions or perform complex calculations when a condition is met.
When it involves 'actions (side effects)': When the purpose is 'something other than obtaining a value', such as screen display, file operations, or database updates.
When logical conditions are complex: When && and are mixed, and it cannot be understood at a glance if kept on one line.
When else if is necessary: When there are three or more options, using a ternary operator becomes very difficult to read.
4. [Caution] Anti-patterns when using ternary operators
Because they are convenient, there are 'forbidden moves' you should avoid.
1. Nesting ternary operatorsThis is the most disliked way of writing them.
// 読みづらい例 const result = score > 90 ? "A" : score > 80 ? "B" : score > 70 ? "C" : "D";
It takes time to understand 'what is branching and how' with this. It is better to use if-else if or switch statements.
2. Combining with complex logical operationsconst canAccess = (user.isAdmin && user.isActive) || (user.isGuest && room.isPublic) ? "許可" : "拒否";
If the conditional expression is too long, it takes effort to find where the ? is. Consider assigning the condition to a variable first or using an if statement.
3. Executing functions within a ternary operator// 避けるべき例 isLoggedin ? redirectToDashboard() : showLoginModal();
If your goal is to perform an 'action' rather than return a value, an if statement conveys your intent more clearly.
5. Common mistakes and countermeasures for compilation errors
Type mismatch (in statically typed languages)A common mistake in Java, C#, TypeScript, etc., is the case where the 'returned types' differ between true and false.
Example that causes an error: condition ? "Success" : 500
Cause: The compiler cannot determine whether the entire expression is a string or a number, resulting in an error. In principle, both types must match.
Ternary operators have a significantly lower precedence than other calculations (+ or *).
Note: When using them within a calculation, always enclose the entire expression in ( ).
-
Example: total = base_price + (has_tax ? tax_amount : 0);
Without parentheses, the calculation order may be unintended, leading to bugs.
5. Summary: Aiming for readable and maintainable code
The ternary operator is by no means a 'tool for reducing typing.' Its true value lies in 'highlighting the main logic of the code by expressing a simple binary choice in a single line.'
When you are unsure whether to use it, please remember the following checklist.
Does the ternary operator fit on a single line?
Can you see the positions of the '?' and ':' at a glance?
Will you be able to understand the meaning of this code immediately when you look at it three months from now?
If the answer is 'No,' do not hesitate to use an if statement. Engineers who write readable code are the true professionals.