- Abstraction
- AI Pair Programming
- Algorithm
- API
- Array
- Array methods
- Booleans
- Callback
- Class
- Class Members
- Closure
- Closure
- Code refactoring
- Comment
- Computer programming
- Conditional statements
- Constant
- Constructor
- Coupling and Cohesion
- Data types
- Debugging
- Decorator
- Dependency
- Destructuring
- Dictionary
- Enum
- Event
- Exception / Error handling
- Function
- Generic / Template
- Higher-order function
- IDE
- Immutability
- Inheritance
- Input validation
- Integer
- Interface
- Iteration patterns
- Legacy code
- Loop
- Machine learning
- Memoization
- Memory and references
- Method
- Module
- Null / Undefined / None
- Null safety / Optional values
- Object
- Object-Oriented Programming (OOP)
- Operator
- Parameter
- Parsing
- Promise and Async/Await
- Prompt Engineering
- Recursion
- Regular expression
- Return statement
- Rollback
- Runtime
- Scope
- Script
- Sequence
- Set
- Spaghetti code
- Spread and Rest operators
- State management
- String
- Switch statement
- Synchronous vs Asynchronous execution
- Syntax
- Technical debt
- Ternary operator
- Testing
- This / Self
- Tuple
- Type casting
- Type conversion
- Variable
- Vibe coding
- Webhook
PROGRAMMING-CONCEPTS
Conditional Statements: Definition, Syntax, and Examples
A conditional statement allows a program to make decisions based on whether a condition is true or false. It tells the computer, “If this happens, do that.”
Conditional logic forms the backbone of programming, enabling everything from login validation and data filtering to game mechanics and website interactivity.
How Conditional Statements Work
A conditional statement checks one or more boolean expressions—conditions that evaluate to true or false. If the condition is true, the program executes a specific block of code. If it’s false, it moves to another option or ends the check entirely.
For example, a program might check if a user entered the right password:
Python
if password == "admin123":
print("Access granted.")
else:
print("Access denied.")
Only one of these two blocks will run, depending on the condition.
Conditional Syntax Across Languages
Python
Python uses if, elif, and else for decision-making:
Python
age = 20
if age >= 18:
print("You can vote.")
elif age == 17:
print("Almost there!")
else:
print("Too young to vote.")
Python’s syntax relies on indentation rather than curly braces, making readability key.
JavaScript / TypeScript
In JavaScript, conditions use parentheses and curly braces.
const score = 85;
if (score >= 90) {
console.log("Excellent");
} else if (score >= 75) {
console.log("Good");
} else {
console.log("Needs improvement");
}
TypeScript adds type safety but keeps the same structure.
let loggedIn: boolean = true;
if (loggedIn) {
console.log("Welcome back!");
} else {
console.log("Please log in.");
}
Swift
Swift’s conditionals closely resemble those in TypeScript but require explicit Bool expressions.
let temperature = 28
if temperature > 30 {
print("It's hot!")
} else if temperature < 10 {
print("It's cold!")
} else {
print("Mild weather")
}
SQL
SQL uses the CASE statement for conditional logic in queries.
SELECT
name,
CASE
WHEN score >= 90 THEN 'A'
WHEN score >= 75 THEN 'B'
ELSE 'C'
END AS grade
FROM students;
This approach adds logic to database results, similar to if/else in programming languages.
When to Use Conditional Statements
Conditional statements are essential whenever a program needs to react to input, data, or changing conditions.
1. Input Validation (Python)
Python
username = input("Enter username: ")
if username == "":
print("Username cannot be empty.")
else:
print("Welcome,", username)
The code checks for valid input before proceeding.
2. User Interaction (React)
React often uses conditional rendering to control what appears on screen.
function Greeting({ loggedIn }) {
return (
<div>
{loggedIn ? <p>Welcome back!</p> : <p>Please sign in.</p>}
</div>
);
}
Here, a single condition decides which message to show.
3. Access Control (JavaScript)
const isAdmin = false;
if (isAdmin) {
console.log("Dashboard access granted.");
} else {
console.log("Restricted area.");
}
Such logic is fundamental in authentication and permissions systems.
4. Decision Logic in SQL
SQL conditionals can shape query results dynamically.
SELECT
order_id,
CASE
WHEN total > 500 THEN 'High Value'
ELSE 'Standard'
END AS order_type
FROM orders;
This allows a single query to categorize records without separate scripts.
Nested and Combined Conditions
Multiple conditions can be combined or nested to handle complex logic.
Python Example
Python
age = 25
has_ticket = True
if age >= 18:
if has_ticket:
print("Entry allowed.")
else:
print("Ticket required.")
else:
print("Underage.")
You can also use logical operators:
- and – both conditions must be true
- or – at least one must be true
- not – reverses a condition’s truth value
JavaScript Example
const age = 20;
const hasID = false;
if (age >= 18 && hasID) {
console.log("Allowed entry");
} else {
console.log("Access denied");
}
These operators let you express precise conditions in compact ways.
Ternary Operator
A ternary operator is a shorthand form of if/else. It’s ideal for simple, one-line conditions.
Example in JavaScript:
const status = age >= 18 ? "Adult" : "Minor";
Example in Python (with conditional expression):
Python
status = "Adult" if age >= 18 else "Minor"
Ternary expressions make short logic more readable, especially in UI rendering and variable assignments.
Common Conditional Mistakes
Even small logical errors can cause conditions to behave unexpectedly. Here are frequent pitfalls:
- Using
=instead of==for comparisons in languages like JavaScript. - Forgetting parentheses around combined conditions.
- Overusing nested conditions instead of simplifying logic.
- Ignoring edge cases (like empty strings or
nullvalues). - Writing overlapping conditions that never allow later checks to run.
Example of a logic error:
if (score > 50) {
console.log("Pass");
} else if (score > 80) { // This will never run
console.log("Excellent");
}
The second condition is unreachable because the first already includes it.
Best Practices
Good conditional design keeps code clear and efficient:
- Write conditions that are easy to read and test.
- Handle edge cases explicitly.
- Avoid deeply nested structures—use early returns or helper functions.
- Use ternary operators for short checks only.
- Comment complex logic to explain intent, not syntax.
Readable conditionals are one of the biggest signs of clean, maintainable code.
Real-World Applications
Conditional logic appears everywhere in modern software:
- Web apps: Handling user sessions, API responses, and form validation.
- Data analysis: Filtering or classifying results.
- Mobile apps: Reacting to gestures, sensors, or permissions.
- Games: Determining collisions, outcomes, or scores.
Every decision a program makes—visible or hidden—runs through conditionals.
Summary
A conditional statement is a decision-making structure that lets a program choose between actions based on true or false conditions. It brings logic, adaptability, and control to code.
Understanding how to use conditionals helps you build programs that respond intelligently—whether displaying content in React, running queries in SQL, or validating input in Python or Swift.
Conditional statements transform static instructions into interactive, flexible software that adapts to the real world.
Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.