What are Nested Conditions?
Nested conditions are conditional statements placed inside other conditional statements. They are used when a decision depends on the outcome of a previous decision. This allows for more complex, multi-level decision-making in your programs.
Why Use Nested Conditions?
Sometimes, your logic needs to ask another question only if the first one passes. In such cases, you use one if
block inside another if
block — that’s called nesting.
Basic Structure
if (condition1) {
// do something
if (condition2) {
// do something more
} else {
// another path
}
} else {
// fallback path
}
Example 1: Age and Citizenship Check
Imagine a voting eligibility check. To vote, a person must be at least 18 years old and a citizen.
if (age >= 18) {
if (citizenship == "yes") {
print("You are eligible to vote")
} else {
print("You must be a citizen to vote")
}
} else {
print("You must be at least 18 years old to vote")
}
Output:
You are eligible to vote
Explanation:
- First, the program checks if the age is 18 or above.
- Only if the age check passes, it checks for citizenship.
- If both pass, the person can vote. Otherwise, it gives a specific message.
Question:
What happens if age is less than 18?
Answer: The inner condition (citizenship check) is never reached. The outer condition fails and directly prints the age-related message.
Example 2: Multi-level Access Check
Suppose we are granting access to a system based on login and role:
if (isLoggedIn == true) {
if (role == "admin") {
print("Access granted: Admin dashboard")
} else if (role == "user") {
print("Access granted: User dashboard")
} else {
print("Access granted: Guest view")
}
} else {
print("Please log in to continue")
}
Output:
Access granted: User dashboard
Explanation:
- First, we ensure the user is logged in.
- If yes, we check the role using nested conditions.
- Based on role, different access levels are granted.
Question:
Can we avoid nesting here?
Answer: In some cases, yes. You could use a flat structure with combined conditions. But nesting improves clarity when one check logically depends on another.
Best Practices
- Keep nesting to 2–3 levels to avoid code complexity.
- Use indentation to visually separate nested blocks.
- Consider using logical operators (AND, OR) to reduce nesting where appropriate.
Recap
- Nested conditions help handle multi-level logic.
- They execute only if the outer condition is true.
- They must be used carefully to keep code readable and maintainable.