Conditional Operator: Short-hand if-else in one line
Learn the ternary operator. Find out how to shorten your code and when to use it instead of classic if-else statements.
Conditional (Ternary) Operator
Programming is about making decisions. Usually, we use if-else statements, but there is a faster way to write simple logic. The conditional operator, known as the ternary operator, allows you to assign a value based on a condition in one short line.
Ternary Operator ( ? : )
How it works: Comparison with if-else
This operator doesn't replace complex logic but is perfect for simple choices.
| Cecha | Feature | Classic if-else |
|---|---|---|
| Syntax | Multi-line, block-based | Single-line, concise |
| Returning | Requires explicit assignment | Returns value directly |
| Readability | High for multiple conditions | High for simple choices |
Code Example
See how the same problem (checking adulthood) is solved in two ways:
1if (age >= 18) { status = 'adult'; } else { status = 'child'; }
1status = (age >= 18) ? 'adult' : 'child';
Common Mistakes and Pitfalls
Nesting Operators
Quiz: Check your knowledge
What will be the result of: int x = (10 > 5) ? 1 : 0; ?
What next?
- Practice converting simple if-else statements into conditional operators.
- Learn about Nullish Coalescing (??) in modern JavaScript.
- Check how the ternary operator works in Python (syntax: x if condition else y).
You might also like
Relational and Logical Operators: How to Compare Data?
Understand how comparison operators work and how to combine conditions using AND, OR, and NOT. Essential knowledge for control statements.
Mathematical Operators: The Foundation of Computing
Learn basic and advanced mathematical operators. Understand how modulo, incrementation works, and why operator precedence matters.
Reserved Keywords: List of Key Terms in IT
Understand what keywords are in programming languages. Learn why you can't use them as variable names and see lists for C++, Java, and Python.